added p2 support package

This commit is contained in:
Peter Li 2026-09-29 02:42:04 -07:00 committed by Peterino2
parent 36f950c68f
commit 005971a8e3
45 changed files with 13941 additions and 1 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
# Ribtech

View File

@ -0,0 +1,22 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
const parser = b.addExecutable(.{
.root_module = b.createModule(.{
.optimize = optimize,
.target = target,
.root_source_file = b.path("tools/interface-parser.zig"),
}),
.name = "parser",
});
const parse_interface_core = b.addRunArtifact(parser);
parse_interface_core.addArgs(&.{ "--input", b.path("src/core/core.zig").getPath(b) });
const generate_headers_step = b.step("generate-interface", "generates interface information from all core apis");
generate_headers_step.dependOn(&parse_interface_core.step);
}

2
engine/p2/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
zig-cache/
zig-out/

21
engine/p2/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Peter Li
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

3
engine/p2/Readme.md Normal file
View File

@ -0,0 +1,3 @@
# P2 - Peterino's stdlib
Contains a bunch of stuff i think is missing from the zig stdlib that is needed for gamedev

47
engine/p2/build.zig Normal file
View File

@ -0,0 +1,47 @@
const std = @import("std");
const bh = @import("bh");
pub fn build(b: *std.Build) void {
const opts = bh.declareOptions(b);
const mod = b.addModule("p2", .{
.target = opts.target,
.optimize = opts.optimize,
.root_source_file = b.path("src/p2.zig"),
});
const filter_option = b.option([]const []const u8, "test-filter", "Skip test that do not match this filter");
const test_filters = filter_option orelse &.{};
const test_step = b.step("test", "test p2");
const tests = b.addTest(.{
.root_module = b.createModule(.{
.target = opts.target,
.optimize = opts.optimize,
.root_source_file = b.path("src/p2.zig"),
}),
.use_llvm = b.option(bool, "llvm", "compiles the tests with llvm "),
.filters = test_filters,
});
tests.root_module.addImport("p2", mod);
const installArtifact = b.addInstallArtifact(tests, .{});
const runArtifact = b.addRunArtifact(tests);
test_step.dependOn(&installArtifact.step);
test_step.dependOn(&runArtifact.step);
if (b.args) |args| {
runArtifact.addArgs(args);
}
b.installArtifact(tests);
const benchmark = b.addExecutable(.{
.name = "queue-benchmark",
.root_module = b.createModule(.{
.target = opts.target,
.optimize = opts.optimize,
.root_source_file = b.path("src/queue-benchmark.zig"),
}),
});
const runBenchmark = b.addRunArtifact(benchmark);
if (b.args) |args| runBenchmark.addArgs(args);
b.step("bench-queues", "Compare one-producer/many-consumer queue throughput").dependOn(&runBenchmark.step);
}

11
engine/p2/build.zig.zon Normal file
View File

@ -0,0 +1,11 @@
.{
.name = .p2,
.version = "0.0.0",
.dependencies = .{
.bh = .{ .path = "../bh" },
},
.paths = .{
"",
},
.fingerprint = 0xa6313a892725ee21,
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
const std = @import("std");

433
engine/p2/src/p2.zig Normal file
View File

@ -0,0 +1,433 @@
// ---- ----
const std = @import("std");
pub const stats = @import("structures/stats.zig");
pub const PoolStatistics = stats.PoolStatistics;
const utils = @import("structures/utils.zig");
pub const getFileExtension = utils.getFileExtension;
pub const getBasePath = utils.getBasePath;
pub const getFolder = utils.getFolder;
pub const getDir = utils.getFolder;
pub const splitSliceWork = utils.splitSliceWork;
pub const BumpArena = @import("structures/bump-arena.zig").BumpArena;
pub const pscopes = @import("structures/pscopes.zig");
pub const dupeString = utils.dupeString;
pub const xxd = @import("utils/xxd.zig");
pub const stringStrip = utils.stringStrip;
pub const xxdWrite = xxd.xxdWrite;
pub const loadFileAlloc = utils.loadFileAlloc;
const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
pub const interface = @import("structures/interface.zig");
pub const MakeInterface = interface.MakeInterface;
pub const Reference = interface.Reference;
pub const refFromPtr = interface.refFromPtr;
pub const assertf = utils.assertf;
pub const asserts = utils.asserts;
pub const assert = utils.assert;
pub const createFileWithPath = utils.createFileWithPath;
pub const makePathAny = utils.makePathAny;
pub const static_structures = @import("structures/static-structures.zig");
pub const StaticVector = static_structures.StaticVector;
pub const math = @import("structures/math.zig");
pub const zm = math.zm;
pub const ring_queue = @import("structures/ring-queue.zig");
pub const RingQueueU = ring_queue.RingQueueU;
pub const RingQueue = ring_queue.RingQueue;
pub const sparse_set = @import("structures/sparse-set.zig");
pub const SparseSet = sparse_set.SparseSet;
pub const SparseMap = sparse_set.SparseMap;
pub const SparseMultiSet = sparse_set.SparseMultiSet;
pub const SparseSetAdvanced = sparse_set.SparseSetAdvanced;
pub const SparseMultiSetAdvanced = sparse_set.SparseMultiSetAdvanced;
pub const SetHandle = sparse_set.SetHandle;
pub const EcsContainerInterface = sparse_set.EcsContainerInterface;
// pub const stack_structures = @import("structures/stack-structures.zig");
pub const index_pool = @import("structures/index-pool.zig");
pub const IndexPoolHandle = index_pool.TypedHandle;
pub const IndexPool = index_pool.IndexPool;
pub const ref_pool = @import("structures/ref-pool.zig");
pub const RefPoolOptions = ref_pool.RefPoolOptions;
pub const RefPool = ref_pool.RefPool;
pub const RefPoolAdvanced = ref_pool.RefPoolAdvanced;
pub const concurrent_queue = @import("structures/concurrent-queue.zig");
pub const ConcurrentQueueU = concurrent_queue.ConcurrentQueueU;
pub const ConcurrentQueueUnmanagedAdvanced = concurrent_queue.ConcurrentQueueUnmanagedAdvanced;
pub const string_pool = @import("structures/string-pool.zig");
pub const RefBuffer = string_pool.RefBuffer;
pub const RefString = string_pool.RefString;
pub const ref_string_map = @import("structures/ref-string-map.zig");
pub const RefStringMap = ref_string_map.RefStringMap;
pub const paged_vector = @import("structures/paged-vector.zig");
pub const PagedVector = paged_vector.PagedVector;
pub const names = @import("structures/names.zig");
pub const NameInvalid = names.NameInvalid;
pub const ComptimeName = names.ComptimeName;
pub const Name = names.Name;
pub const StaticName = names.StaticName;
pub const MakeName = names.MakeName;
pub const DefineName = names.DefineName;
pub const createNameRegistry = names.createNameRegistry;
pub const destroyNameRegistry = names.destroyNameRegistry;
pub const setNameRegistry = names.setNameRegistry;
pub const NameRegistry = names.NameRegistry;
pub const spans = @import("structures/spans.zig");
pub const MergedSpans = spans.MergedSpans;
pub const Span = spans.Span;
pub const shell = @import("utils/shell.zig");
pub fn sharedLibNameAlloc(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
const os_tag = @import("builtin").os.tag;
var suffix: []const u8 = "dll";
var prefix: []const u8 = "";
if (os_tag == .linux) {
prefix = "lib";
suffix = "so";
} else if (os_tag == .macos) {
suffix = "dylib";
prefix = "lib";
}
const path = try std.fmt.allocPrint(allocator, "{s}{s}.{s}", .{ prefix, s, suffix });
return path;
}
comptime {
std.testing.refAllDecls(utils);
std.testing.refAllDecls(static_structures);
std.testing.refAllDecls(ring_queue);
std.testing.refAllDecls(sparse_set);
// std.testing.refAllDecls(stack_structures);
std.testing.refAllDecls(index_pool);
std.testing.refAllDecls(concurrent_queue);
std.testing.refAllDecls(@import("structures/spmc-submission-queue.zig"));
std.testing.refAllDecls(string_pool);
std.testing.refAllDecls(ref_string_map);
std.testing.refAllDecls(spans);
}
// ---- aliases ----
pub const ObjectHandle = SetHandle;
pub inline fn u32_to_slice(array: *u32) []u8 {
var slice: []u8 = undefined;
slice.ptr = @ptrCast(array);
slice.len = 4;
return slice;
}
pub inline fn u64_to_slice(array: *u64) []u8 {
var slice: []u8 = undefined;
slice.ptr = @ptrCast(array);
slice.len = 8;
return slice;
}
pub inline fn arrayTo_u32(array: anytype) u32 {
return @as(*const u32, @ptrCast(@alignCast(&array))).*;
}
pub inline fn arrayTo_u64(array: anytype) u64 {
return @as(*const u64, @ptrCast(@alignCast(&array))).*;
}
// ---- tests ----
test "multi-sparse-basic" {
const allocator = std.testing.allocator;
const TestStructField = struct {
x: u32,
};
const TestStruct = struct {
field1: usize,
structField: TestStructField,
};
var testSet = SparseMultiSet(TestStruct).init(allocator);
defer testSet.deinit();
const sparseHandle = try testSet.createObject(.{ .field1 = 1, .structField = .{ .x = 12 } });
const sparseHandle1 = try testSet.createObject(.{ .field1 = 2, .structField = .{ .x = 34 } });
const sparseHandle2 = try testSet.createObject(.{ .field1 = 3, .structField = .{ .x = 56 } });
std.debug.print("handle: {any}\n", .{testSet.get(sparseHandle, .field1).?.*});
std.debug.print("handle1: {any}\n", .{testSet.get(sparseHandle1, .field1).?.*});
std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*});
_ = testSet.destroyObject(sparseHandle);
std.debug.print("handle1: {any}\n", .{testSet.get(sparseHandle1, .field1).?.*});
std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*});
}
// As RibTech is primarily a playground for me to learn and practice programming,
// There will be some implementations of basic data structures. For fun ofc
pub fn AppendToArrayListUnique(list: anytype, value: anytype) !void {
for (list.items) |v| {
if (v == value)
return;
}
try list.append(value);
}
fn printSetHandle(s: SetHandle) void {
std.debug.print("{any}\n", .{s});
}
test "sparse-set" {
std.debug.print("\n", .{});
const Payload = struct {
name: []const u8,
v: u32,
};
const PayloadSet = SparseSet(Payload);
const expect = std.testing.expect;
var set = PayloadSet.init(std.testing.allocator);
defer set.deinit();
var set2 = PayloadSet.init(std.testing.allocator);
defer set2.deinit();
const setHandle = (try set.createAndGet(.{ .name = "object1", .v = 0 })).handle;
printSetHandle(setHandle);
const setHandle1 = (try set.createObject(.{ .name = "object2", .v = 1 }));
printSetHandle(setHandle1);
const setHandle2 = (try set.createObject(.{ .name = "object3", .v = 2 }));
printSetHandle(setHandle2);
const setHandle3 = (try set.createObject(.{ .name = "object4", .v = 3 }));
printSetHandle(setHandle3);
const set2Handle1 = (try set2.createWithHandle(setHandle3, set.get(setHandle2).?.*)).handle;
std.debug.print("set2 handle: \n", .{});
printSetHandle(set2Handle1);
for (set.dense.items) |entry| {
std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name });
}
std.debug.print("\ndestroying handle\n", .{});
set.destroyObject(setHandle);
for (set.dense.items) |entry| {
std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name });
}
try expect(set.get(setHandle) == null);
try expect(set.get(setHandle1).?.v == 1);
try expect(set.get(setHandle2).?.v == 2);
try expect(set.get(setHandle3).?.v == 3);
std.debug.print("\ndestroying handle\n", .{});
set.destroyObject(setHandle1);
for (set.dense.items) |entry| {
std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name });
}
try expect(set.get(setHandle) == null);
try expect(set.get(setHandle1) == null);
try expect(set.get(setHandle2).?.v == 2);
try expect(set.get(setHandle3).?.v == 3);
std.debug.print("\ndestroying handle\n", .{});
set.destroyObject(setHandle2);
for (set.dense.items) |entry| {
std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name });
}
try expect(set.get(setHandle) == null);
try expect(set.get(setHandle1) == null);
try expect(set.get(setHandle3).?.v == 3);
try expect(set.get(setHandle2) == null);
std.debug.print("\ndestroying handle\n", .{});
set.destroyObject(setHandle3);
for (set.dense.items) |entry| {
std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name });
}
try expect(set.get(setHandle) == null);
try expect(set.get(setHandle1) == null);
try expect(set.get(setHandle2) == null);
try expect(set.get(setHandle3) == null);
try expect(set.dense.items.len == 0);
}
test "ringBuffer" {
std.debug.print("\nbuffer test: filling a ring buffer\n", .{});
const allocator = std.testing.allocator;
var b = try RingQueueU(u32).init(allocator, 4);
defer b.deinit(allocator);
const expect = std.testing.expect;
try b.push(1);
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
try b.push(2);
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
try b.push(3);
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
try expect(b.count() == 3);
std.debug.print("popping: {d}\n", .{b.pop().?});
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
try expect(b.count() == 2);
std.debug.print("popping: {d}\n", .{b.pop().?});
try expect(b.count() == 1);
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
std.debug.print("popping: {d}\n", .{b.pop().?});
try expect(b.count() == 0);
try expect(b.pop() == null);
std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail });
try std.testing.expect(b.head == b.tail);
try std.testing.expect(b.isEmpty());
try b.push(11);
std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len });
try expect(b.count() == 1);
try b.push(12);
std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len });
try expect(b.count() == 2);
try b.push(13);
std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len });
try expect(b.count() == 3);
try b.push(14);
std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len });
try expect(b.head == 3);
try expect(b.count() == 4);
try expect(b.tail == ((b.head + 4) % b.buffer.len));
try expect(b.at(0).? == b.peek().?);
const newSize = b.buffer.len * 4;
try b.resize(allocator, newSize); // grow that shit, expect the new size to be size + 1
try expect(b.capacity() == newSize);
try expect(b.buffer.len == newSize + 1);
var errorHit: bool = false;
b.resize(allocator, 2) catch |e| {
errorHit = true;
try expect(e == error.AllocSizeTooSmall);
std.debug.print("{any}\n", .{e});
};
try expect(errorHit);
try expect(b.peekBack().?.* == 14);
try expect(b.atBack(1).?.* == 14);
try expect(b.atBack(2).?.* == 13);
try expect(b.atBack(3).?.* == 12);
try expect(b.atBack(4).?.* == 11);
try b.pushFront(44);
try expect(b.count() == 5);
try expect(b.peek().?.* == 44);
}
test "managed ring queue uses stored io mutex" {
const allocator = std.testing.allocator;
const expect = std.testing.expect;
var queue = try RingQueue(u32).init(allocator, std.testing.io, 2);
defer queue.deinit();
queue.allowRegrow();
try queue.pushLocked(1);
try queue.pushLocked(2);
try queue.pushLocked(3);
try expect(queue.count() == 3);
try expect(queue.popFromLocked().? == 1);
queue.lock();
defer queue.unlock();
try expect(queue.popFromUnlocked().? == 2);
try expect(queue.popFromUnlocked().? == 3);
try expect(queue.popFromUnlocked() == null);
}
test "spin child process echo" {
const io = std.testing.io;
{
std.debug.print("spin child process\n", .{});
const process = try shell.ShellProcess.init(std.testing.allocator, io, &.{ "echo", "lmao 2 nova" });
defer process.deinit();
std.debug.print("child process created: {any}\n", .{process.argv});
}
{
std.debug.print("spin child process 2\n", .{});
const process = try shell.ShellProcess.initCmd(std.testing.allocator, io, "echo lmao2nova -target='lmao 3 nova'");
defer process.deinit();
std.debug.print("{any}\n", .{process.argv});
}
}
test "ring queue regrow remains opt-in" {
const allocator = std.testing.allocator;
const expect = std.testing.expect;
const expectError = std.testing.expectError;
var fixed = try RingQueueU(u32).init(allocator, 1);
defer fixed.deinit(allocator);
try fixed.push(1);
try expectError(error.QueueIsFull, fixed.push(2));
try expect(fixed.capacity() == 1);
var regrow = try RingQueueU(u32).init(allocator, 1);
defer regrow.deinit(allocator);
regrow.allowRegrow();
try regrow.push(10);
try regrow.push(20);
try expect(regrow.capacity() >= 2);
try expect(regrow.count() == 2);
try expect(regrow.pop().? == 10);
try expect(regrow.pop().? == 20);
try expect(regrow.pop() == null);
}
test "ring queue regrow supports pushFront ordering" {
const allocator = std.testing.allocator;
const expect = std.testing.expect;
var queue = try RingQueueU(u32).init(allocator, 2);
defer queue.deinit(allocator);
queue.allowRegrow();
try queue.push(2);
try queue.push(3);
try queue.pushFront(1);
try expect(queue.capacity() >= 3);
try expect(queue.count() == 3);
try expect(queue.pop().? == 1);
try expect(queue.pop().? == 2);
try expect(queue.pop().? == 3);
try expect(queue.isEmpty());
}

View File

@ -0,0 +1,117 @@
//! Frozen pre-fetchSub implementation for queue-benchmark.zig only.
//! Do not use as a production queue or update alongside the live implementation.
const std = @import("std");
pub const PackedState = packed struct(u32) {
remaining_items: u24 = 0, // Unclaimed entries.
active_readers: u8 = 0, // Consumers copying descriptors.
};
/// Single-producer, multiple-consumer batch mailbox.
///
/// Keep the mailbox at a stable address once shared.
/// Values are copied
///
/// usage:
///
/// producer:
/// queue.push(.{.x = 4});
///
/// consumers:
/// while(alive) {
/// if(queue.tryTake())|value|
/// {
/// self.dowork(value);
/// }
/// else
/// {
/// chillout();
/// }
/// }
///
pub fn CommitQueue(comptime T: type) type {
return struct {
allocator: std.mem.Allocator,
state: std.atomic.Value(PackedState) = .init(.{}),
active: std.ArrayList(T) = .empty,
back: std.ArrayList(T) = .empty,
pub fn init(allocator: std.mem.Allocator) @This() {
return .{ .allocator = allocator };
}
pub fn deinit(self: *@This()) void {
while (!self.canSubmit()) std.atomic.spinLoopHint();
self.active.deinit(self.allocator);
self.back.deinit(self.allocator);
}
/// Producer only. Grows the private backbuffer as needed.
pub fn push(self: *@This(), item: T) !void {
if (self.back.items.len == std.math.maxInt(u24)) return error.BatchFull;
try self.back.append(self.allocator, item);
}
/// Consumers. Null means the batch is empty or all 255 reader pins are in use.
pub fn tryTake(self: *@This()) ?T {
var s = self.state.load(.monotonic);
while (true) {
if (s.remaining_items == 0 or s.active_readers == std.math.maxInt(u8))
return null;
// Claim one entry and pin its batch atomically.
var desired = s;
desired.remaining_items -= 1;
desired.active_readers += 1;
if (self.state.cmpxchgWeak(s, desired, .acquire, .monotonic)) |observed| {
s = observed;
continue;
}
// Read metadata only after successfully pinning.
const index = self.active.items.len - @as(usize, s.remaining_items);
const item = self.active.items[index];
self.releaseReader();
return item;
}
}
/// Historical release loop, intentionally frozen for A/B measurement.
fn releaseReader(self: *@This()) void {
var s = self.state.load(.monotonic);
var bailOut: u32 = 100000000;
while (bailOut > 0) : (bailOut -= 1) {
var desired = s;
desired.active_readers -= 1;
if (self.state.cmpxchgWeak(s, desired, .release, .monotonic)) |observed| {
s = observed;
continue;
}
return;
}
}
pub fn canSubmit(self: *const @This()) bool {
const state = self.state.load(.acquire);
return state.remaining_items == 0 and state.active_readers == 0;
}
/// Must only be called Producer only.
/// publishes the backbuffer to all consumers,
pub fn submit(self: *@This()) void {
while (!self.canSubmit()) {
std.atomic.spinLoopHint();
}
std.mem.swap(@TypeOf(self.active), &self.active, &self.back);
self.back.clearRetainingCapacity();
self.state.store(.{ .remaining_items = @intCast(self.active.items.len) }, .release);
}
};
}

View File

@ -0,0 +1,203 @@
//! One producer, N consumers. Run through `zig build bench-queues` in lib/p2.
const std = @import("std");
const CommitQueue = @import("structures/spmc-submission-queue.zig").CommitQueue;
const ConcurrentQueue = @import("structures/concurrent-queue.zig").ConcurrentQueueU;
const CasCommitQueue = @import("queue-benchmark-cas-baseline.zig").CommitQueue;
const Kind = enum { commit, concurrent, commit_cas };
fn Bench(comptime kind: Kind, comptime wordCount: usize, comptime work: usize) type {
return struct {
const Item = struct { words: [wordCount]u64 };
const Queue = switch (kind) {
.commit => CommitQueue(Item, .{ .ChunkSize = 256 }),
.commit_cas => CasCommitQueue(Item),
.concurrent => ConcurrentQueue(Item),
};
const Worker = struct {
queue: *Queue,
gate: *std.Io.Event,
ready: *std.atomic.Value(usize),
producerDone: *std.atomic.Value(bool),
io: std.Io,
count: u64 align(64) = 0,
sum: u64 = 0,
xor: u64 = 0,
digest: u64 = 0,
bad: bool = false,
fn run(self: *@This()) void {
_ = self.ready.fetchAdd(1, .release);
self.gate.waitUncancelable(self.io);
var output: [256]Item = undefined;
var draining = false;
while (true) {
const items: []const Item = if (kind == .commit)
self.queue.maybeTake(&output)
else blk: {
const item = if (kind == .commit_cas) self.queue.tryTake() else self.queue.pop();
if (item) |value| {
output[0] = value;
break :blk output[0..1];
}
break :blk &.{};
};
for (items) |item| {
const id = item.words[0];
self.count += 1;
self.sum +%= id;
self.xor ^= id;
for (item.words[1..], 1..) |value, lane| {
if (value != id ^ @as(u64, @intCast(lane))) self.bad = true;
}
var result = id;
for (0..work) |_| result = (result ^ (result >> 13)) *% 0x9e3779b97f4a7c15;
self.digest +%= result;
}
if (items.len == 0) {
if (draining) return;
// After acquiring completion, recheck the queue before
// exiting: the first empty observation may predate publication.
draining = self.producerDone.load(.acquire);
std.atomic.spinLoopHint();
}
}
}
};
fn makeItem(id: u64) Item {
var item: Item = undefined;
for (&item.words, 0..) |*value, lane| value.* = id ^ @as(u64, @intCast(lane));
return item;
}
fn flush(queue: *Queue) void {
if (kind != .concurrent) queue.submit();
}
fn measure(gpa: std.mem.Allocator, io: std.Io, consumers: usize, batch: usize, milliseconds: i64) !f64 {
const capacity = @max(batch, consumers);
var queue = if (kind != .concurrent) Queue.init(gpa) else try Queue.initCapacity(gpa, capacity * 2);
defer if (kind != .concurrent) queue.deinit() else queue.deinit(gpa);
if (kind != .concurrent) {
try queue.active.ensureTotalCapacity(gpa, capacity);
try queue.back.ensureTotalCapacity(gpa, capacity);
}
var gate: std.Io.Event = .unset;
var ready: std.atomic.Value(usize) = .init(0);
var producerDone: std.atomic.Value(bool) = .init(false);
var workers: [8]Worker = undefined;
var threads: [8]std.Thread = undefined;
var spawned: usize = 0;
// Even a partial spawn must release and shut down existing workers.
errdefer {
gate.set(io);
flush(&queue);
producerDone.store(true, .release);
for (threads[0..spawned]) |thread| thread.join();
}
for (0..consumers) |i| {
workers[i] = .{ .queue = &queue, .gate = &gate, .ready = &ready, .producerDone = &producerDone, .io = io };
threads[i] = try std.Thread.spawn(.{}, Worker.run, .{&workers[i]});
spawned += 1;
}
while (ready.load(.acquire) != consumers) std.atomic.spinLoopHint();
const begin = std.Io.Timestamp.now(io, .awake);
gate.set(io);
var produced: u64 = 0;
var expectedSum: u64 = 0;
var expectedXor: u64 = 0;
var batches: usize = 0;
while (true) {
for (0..batch) |_| {
try queue.push(makeItem(produced));
expectedSum +%= produced;
expectedXor ^= produced;
produced += 1;
}
flush(&queue);
batches += 1;
// Amortize clock overhead for small batches; check every large batch
// so a 65K batch does not force millions of extra items per sample.
const clockInterval: usize = if (batch >= 10000) 1 else 64;
if (batches % clockInterval == 0 and begin.durationTo(std.Io.Timestamp.now(io, .awake)).toMilliseconds() >= milliseconds) break;
}
producerDone.store(true, .release);
for (threads[0..consumers]) |thread| thread.join();
spawned = 0;
const elapsed = begin.durationTo(std.Io.Timestamp.now(io, .awake)).toNanoseconds();
var count: u64 = 0;
var sum: u64 = 0;
var xor: u64 = 0;
for (workers[0..consumers]) |*worker| {
if (worker.bad) return error.CorruptPayload;
count += worker.count;
sum +%= worker.sum;
xor ^= worker.xor;
std.mem.doNotOptimizeAway(worker.digest);
}
if (count != produced or sum != expectedSum or xor != expectedXor) return error.IncorrectDelivery;
return @as(f64, @floatFromInt(count)) * 1000.0 / @as(f64, @floatFromInt(elapsed));
}
};
}
fn scenario(comptime words: usize, comptime work: usize, init: std.process.Init, consumers: usize, batch: usize, sampleMs: i64, compareCas: bool) !void {
if (compareCas) return scenarioAgainst(words, work, .commit_cas, init, consumers, batch, sampleMs);
return scenarioAgainst(words, work, .concurrent, init, consumers, batch, sampleMs);
}
fn scenarioAgainst(comptime words: usize, comptime work: usize, comptime other: Kind, init: std.process.Init, consumers: usize, batch: usize, sampleMs: i64) !void {
const S = Bench(.commit, words, work);
const C = Bench(other, words, work);
_ = try S.measure(init.gpa, init.io, consumers, batch, 100);
_ = try C.measure(init.gpa, init.io, consumers, batch, 100);
for (0..3) |sample| {
var s: f64 = undefined;
var c: f64 = undefined;
if (sample % 2 == 0) {
s = try S.measure(init.gpa, init.io, consumers, batch, sampleMs);
c = try C.measure(init.gpa, init.io, consumers, batch, sampleMs);
} else {
c = try C.measure(init.gpa, init.io, consumers, batch, sampleMs);
s = try S.measure(init.gpa, init.io, consumers, batch, sampleMs);
}
std.debug.print("{d},{d},{d},{d},{d},commit,{d:.6}\n", .{ consumers, batch, words * 8, work, sample, s });
std.debug.print("{d},{d},{d},{d},{d},{s},{d:.6}\n", .{ consumers, batch, words * 8, work, sample, @tagName(other), c });
}
}
pub fn main(init: std.process.Init) !void {
var sampleMs: i64 = 400;
var minConsumers: usize = 1;
var largeBatches = false;
var compareCas = false;
const args = try init.minimal.args.toSlice(init.arena.allocator());
for (args[1..]) |arg| {
if (std.mem.startsWith(u8, arg, "--sample-ms=")) {
sampleMs = try std.fmt.parseInt(i64, arg["--sample-ms=".len..], 10);
if (sampleMs < 1) return error.InvalidSampleDuration;
} else if (std.mem.startsWith(u8, arg, "--min-consumers=")) {
minConsumers = try std.fmt.parseInt(usize, arg["--min-consumers=".len..], 10);
if (minConsumers < 1 or minConsumers > 8) return error.InvalidConsumerCount;
} else if (std.mem.eql(u8, arg, "--large-batches")) {
largeBatches = true;
} else if (std.mem.eql(u8, arg, "--compare-cas")) {
compareCas = true;
} else return error.UnknownArgument;
}
std.debug.print("consumers,batch,payload_bytes,work_iterations,sample,queue,million_items_per_second\n", .{});
for ([_]usize{ 1, 2, 4, 8 }) |consumers| {
if (consumers < minConsumers) continue;
if (largeBatches) {
for ([_]usize{ 10000, 65536 }) |batch| {
try scenario(2, 0, init, consumers, batch, sampleMs, compareCas);
try scenario(32, 0, init, consumers, batch, sampleMs, compareCas);
try scenario(2, 256, init, consumers, batch, sampleMs, compareCas);
}
} else {
for ([_]usize{ 1, 64, 1024 }) |batch| try scenario(2, 0, init, consumers, batch, sampleMs, compareCas);
try scenario(32, 0, init, consumers, 256, sampleMs, compareCas);
try scenario(2, 256, init, consumers, 256, sampleMs, compareCas);
}
}
}

View File

@ -0,0 +1,161 @@
const std = @import("std");
const stats = @import("stats.zig");
const paged_vector = @import("paged-vector.zig");
const PagedVectorAdvanced = paged_vector.PagedVectorAdvanced;
// mutex based, fast bump-only allocator
pub const BumpArena = struct {
const PageSize = 8192 * 2;
const SmallAllocPages = paged_vector.PagedVectorAdvanced([PageSize]u8, 1);
smallBumpOffset: usize = 0,
pageIndex: usize = 0,
allocatedBytes: usize = 0,
allocCount: usize = 0,
backing: std.mem.Allocator,
io_context: std.Io,
small: SmallAllocPages,
large: std.heap.ArenaAllocator,
mutex: std.Io.Mutex,
pub var vtable: std.mem.Allocator.VTable = .{
.alloc = alloc,
.free = free,
.resize = resize,
.remap = std.mem.Allocator.noRemap,
};
pub fn usage(self: *@This()) usize {
return self.allocatedBytes;
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
return .{
.statName = "BumpArena",
.instanceCount = self.allocCount,
.memoryReserved = self.small.pages.items.len * PageSize +
self.small.pages.capacity * @sizeOf(usize) +
self.large.queryCapacity(),
.memoryUsed = self.allocatedBytes,
};
}
pub fn init(backing: std.mem.Allocator, io_context: std.Io) !@This() {
return .{
.backing = backing,
.io_context = io_context,
.small = try SmallAllocPages.init(backing),
.large = std.heap.ArenaAllocator.init(backing),
.mutex = .init,
};
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
pub fn deinit(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
self.small.deinit(self.backing);
self.large.deinit();
}
fn respectAlignment(offset: usize, alignment: std.mem.Alignment) usize {
if (offset == 0) {
return 0;
}
const a: usize = @intCast(@as(usize, @intCast(1)) << @as(u6, @truncate(@intFromEnum(alignment))));
return ((offset / a) + 1) * @as(usize, @intCast(a));
}
pub fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
self.allocatedBytes += len;
self.allocCount += 1;
if (len > 4096) {
return self.largeAllocator().vtable.alloc(self.largeAllocator().ptr, len, ptr_align, ret_addr);
} else {
const currentPageFree = PageSize - self.smallBumpOffset;
if (len < currentPageFree) {
const alignedOffset = respectAlignment(self.smallBumpOffset, ptr_align);
const rv = self.small.getMutable(self.pageIndex)[alignedOffset .. alignedOffset + len];
// std.debug.print("original offset {d} respected offset {d} alignment {d} address: {x}\n", .{ self.smallBumpOffset, alignedOffset, ptr_align, @intFromPtr(rv.ptr) });
self.smallBumpOffset = alignedOffset + len;
return rv.ptr;
} else {
// new allocation exceeds the remaining size of this page
self.pageIndex += 1;
self.smallBumpOffset = len;
self.small.append(self.backing, undefined) catch return null;
return self.small.getMutable(self.pageIndex)[0..len].ptr;
}
}
unreachable;
}
inline fn largeAllocator(self: *@This()) std.mem.Allocator {
return self.large.allocator();
}
pub fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void {
// it's a bump allocator, it does nothing on free.
_ = ctx;
_ = buf;
_ = buf_align;
_ = ret_addr;
}
// do not support resize in place.
pub fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
_ = buf;
_ = buf_align;
_ = new_len;
_ = ret_addr;
return false;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return .{ .ptr = self, .vtable = &vtable };
}
pub fn reset(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
_ = self.large.reset(.free_all);
self.small.reset(self.backing);
self.smallBumpOffset = 0;
self.pageIndex = 0;
self.allocatedBytes = 0;
self.allocCount = 0;
}
};
test "bump-it-uppp" {
var arena = try BumpArena.init(std.testing.allocator, std.testing.io);
defer arena.deinit();
}
test "reset clears usage" {
var arena = try BumpArena.init(std.testing.allocator, std.testing.io);
defer arena.deinit();
const allocator = arena.allocator();
const mem = allocator.alloc(u8, 128) catch unreachable;
defer _ = mem;
try std.testing.expect(arena.usage() >= 128);
arena.reset();
try std.testing.expectEqual(@as(usize, 0), arena.usage());
}

View File

@ -0,0 +1,280 @@
const std = @import("std");
const utils = @import("utils.zig");
const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const asserts = utils.asserts;
const Atomic = std.atomic.Value;
pub const ConcurrentQueueError = error{
CorruptedState,
QueueIsEmpty,
QueueIsFull,
};
pub fn ConcurrentQueueU(comptime T: type) type {
return ConcurrentQueueUnmanagedAdvanced(T, .{});
}
pub fn ConcurrentQueueAssert(comptime T: type) type {
return ConcurrentQueueUnmanagedAdvanced(T, .{ .allowAsserts = true });
}
// lock-free concurrent queue, fixed capacity,
// will never resize.
//
// new version based on
// https://github.com/rigtorp/MPMCQueue
pub const ConcurrentStatus = packed struct(usize) {
alive: bool = false,
generation: u63 = 0,
};
pub fn ConcurrentQueueUnmanagedAdvanced(comptime T: type, comptime opts: struct {
allowAsserts: bool = false,
debug: bool = false,
}) type {
return struct {
data: []align(64) T align(64),
status: []align(64) Atomic(ConcurrentStatus) align(64), // 1 = valid, 0 = invalid,
pushId: Atomic(usize) align(64),
popId: Atomic(usize) align(64),
// tail points to next free slot
// head points to the next one to pop
pub fn initCapacity(allocator: std.mem.Allocator, cap: usize) !@This() {
const new = @This(){
.data = try allocator.alignedAlloc(T, .@"64", cap),
.status = try allocator.alignedAlloc(Atomic(ConcurrentStatus), .@"64", cap),
.pushId = Atomic(usize).init(0),
.popId = Atomic(usize).init(0),
};
for (new.status) |*s| {
s.* = Atomic(ConcurrentStatus).init(std.mem.zeroes(ConcurrentStatus));
}
return new;
}
pub fn push(self: *@This(), value: T) !void {
const pushId = self.pushId.fetchAdd(1, .acq_rel);
const slot = @mod(pushId, self.data.len);
const newStatus = ConcurrentStatus{
.generation = @intCast(@divTrunc(pushId, self.data.len)),
.alive = true,
};
if (opts.debug) std.log.warn("pushing {d}", .{pushId});
while (true) {
const status = self.status[slot].load(.acquire);
if (status.generation == newStatus.generation and status.alive == false) {
break;
}
std.atomic.spinLoopHint();
}
if (opts.debug) std.log.warn("pushed {d}", .{pushId});
self.data[slot] = value;
self.status[slot].store(newStatus, .release);
}
// pop the value from the queue, moves the head forward
pub fn pop(self: *@This()) ?T { // things are empty
const popId = blk: while (true) {
const popId = self.popId.load(.acquire);
const pushId = self.pushId.load(.acquire);
if (popId >= pushId) return null;
if (self.popId.cmpxchgWeak(popId, popId + 1, .acq_rel, .acquire) == null) {
break :blk popId;
}
std.atomic.spinLoopHint();
};
const slot = @mod(popId, self.data.len);
const expectedStatus = ConcurrentStatus{
.generation = @intCast(@divTrunc(popId, self.data.len)),
.alive = true,
};
if (opts.debug) std.log.warn("popping {d}", .{popId});
while (true) {
const status = self.status[slot].load(.acquire);
if (status.generation == expectedStatus.generation and status.alive) {
break;
}
std.atomic.spinLoopHint();
}
if (opts.debug) std.log.warn("popped {d}", .{popId});
const value = self.data[slot];
self.status[slot].store(.{ .alive = false, .generation = expectedStatus.generation +% 1 }, .release);
return value;
}
pub fn count(self: @This()) usize {
const head = self.pushId.load(.acquire);
const tail = self.popId.load(.acquire);
if (opts.debug)
std.log.warn("count {d}", .{head - tail});
if (opts.allowAsserts) {
asserts(tail <= head, "tail > head in concurrent queue, this shouldnt ever happen", .{}, "concurrent queue assert");
}
return head - tail;
}
pub fn capacity(self: @This()) usize {
return self.data.len;
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
allocator.free(self.data);
allocator.free(self.status);
}
};
}
test "concurrent queue basic correctness test" {
const Info = struct {
x: u32 = 0,
};
const allocator = std.testing.allocator;
var y = try ConcurrentQueueUnmanagedAdvanced(Info, .{ .allowAsserts = true, .debug = true }).initCapacity(allocator, 420);
defer y.deinit(allocator);
try y.push(.{});
try y.push(.{ .x = 1 });
try y.push(.{ .x = 2 });
try y.push(.{ .x = 1 });
try utils.assertf(y.count() == 4, "expected there to be {d} elements in queue, we saw {d}", .{ 4, y.count() });
_ = y.pop();
_ = y.pop();
_ = y.pop();
_ = y.pop();
try utils.assertf(y.count() == 0, "expected there to be {d} elements in queue, we saw {d}", .{ 0, y.count() });
var x = try ConcurrentQueueU(Info).initCapacity(allocator, 12);
defer x.deinit(allocator);
try x.push(.{ .x = 0 });
try x.push(.{ .x = 1 });
try x.push(.{ .x = 2 });
try x.push(.{ .x = 3 });
try x.push(.{ .x = 4 });
try x.push(.{ .x = 5 });
try x.push(.{ .x = 6 });
try x.push(.{ .x = 7 });
try x.push(.{ .x = 8 });
try x.push(.{ .x = 9 });
try x.push(.{ .x = 10 });
// const maybeError = x.push(.{ .x = 11 });
// try utils.assertf(maybeError == ConcurrentQueueError.QueueIsFull, "Expected queue to have an error", .{});
}
test "concurrent queue multiple producer single consumer" {
// 1. create multiple threads
const threadCount = 24;
const Payload = struct {
x: i64 = 0,
arb: [4096]u8 = undefined,
};
const QueueType = ConcurrentQueueUnmanagedAdvanced(Payload, .{ .debug = false, .allowAsserts = true });
const Wrap = struct {
pub fn threadFunc(queueRef: *QueueType, id: i64, exitSignal: *Atomic(bool), pushedCountResults: *Atomic(i64)) void {
var pushedCount: i64 = 0;
while (!exitSignal.load(.monotonic)) {
queueRef.push(.{
.x = id + pushedCount,
}) catch unreachable;
pushedCount += 1;
}
_ = pushedCountResults.fetchAdd(pushedCount, .seq_cst);
}
};
var threads: [threadCount]std.Thread = undefined;
var testQueue = try QueueType.initCapacity(std.testing.allocator, 4096 * 4);
defer testQueue.deinit(std.testing.allocator);
var exitSignalAtomic = Atomic(bool).init(false);
var pushedCountResults = Atomic(i64).init(0);
for (0..threadCount) |i| {
threads[i] = try std.Thread.spawn(.{}, Wrap.threadFunc, .{ &testQueue, @as(i64, @intCast(i * 10000)), &exitSignalAtomic, &pushedCountResults });
}
// 5 second message pump test
var oldTime: f64 = test_getTime(std.testing.io);
// 10 second test, 5 seconds of input, 5 seconds of drain
const startTime: f64 = 2.2;
var timeLeft: f64 = startTime;
var poppedCount: i64 = 0;
var signaled: bool = false;
while (timeLeft > 0 or testQueue.count() > 0) {
const newTime = test_getTime(std.testing.io);
const deltaTime = newTime - oldTime;
if (timeLeft - deltaTime < 0.0 and !signaled) {
signaled = true;
exitSignalAtomic.store(true, .seq_cst);
}
timeLeft -= deltaTime;
oldTime = newTime;
if (testQueue.pop()) |x| {
_ = x;
poppedCount += 1;
}
std.atomic.spinLoopHint();
}
for (0..threadCount) |i| {
threads[i].join();
}
std.debug.print("popped {d} entries in {d} seconds payloadSize: {d} dataRate: {d:.3} MiB/s time/event {d:.3} us \n", .{
poppedCount,
startTime,
@sizeOf(Payload),
@as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)) * @sizeOf(Payload))) / startTime / 1024 / 1024,
startTime / @as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)))) * 1000 * 1000,
});
try utils.assertf(
poppedCount == pushedCountResults.load(.seq_cst),
"mismatched, we popped {d} records while the workers pushed {d}",
.{
poppedCount,
pushedCountResults.load(.seq_cst),
},
);
}
fn test_getTime(io: std.Io) f64 {
return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toMilliseconds())) / 1000;
}

View File

@ -0,0 +1,71 @@
pub const std = @import("std");
pub const CountingAllocatorContext = struct {
wrappedAllocator: std.mem.Allocator = undefined,
alloc_count: usize = 0,
free_count: usize = 0,
alloc_bytes: usize = 0,
free_bytes: usize = 0,
memory_usage: usize = 0,
const vtable: std.mem.Allocator.VTable = .{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
};
pub fn allocator(self: *@This(), wrappedAllocator: std.mem.Allocator) std.mem.Allocator {
self.wrappedAllocator = wrappedAllocator;
return .{
.ptr = self,
.vtable = &vtable,
};
}
fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
const ptr = self.wrappedAllocator.rawAlloc(len, alignment, ret_addr) orelse return null;
self.alloc_count += 1;
self.alloc_bytes += len;
self.memory_usage += len;
return ptr;
}
fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (!self.wrappedAllocator.rawResize(memory, alignment, new_len, ret_addr)) {
return false;
}
self.recordResize(memory.len, new_len);
return true;
}
fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
const ptr = self.wrappedAllocator.rawRemap(memory, alignment, new_len, ret_addr) orelse return null;
self.recordResize(memory.len, new_len);
return ptr;
}
fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
self.free_count += 1;
self.free_bytes += memory.len;
self.memory_usage -= @min(self.memory_usage, memory.len);
self.wrappedAllocator.rawFree(memory, alignment, ret_addr);
}
fn recordResize(self: *@This(), old_len: usize, new_len: usize) void {
if (new_len > old_len) {
const delta = new_len - old_len;
self.alloc_bytes += delta;
self.memory_usage += delta;
} else if (old_len > new_len) {
const delta = old_len - new_len;
self.free_bytes += delta;
self.memory_usage -= @min(self.memory_usage, delta);
}
}
};

View File

@ -0,0 +1,431 @@
const std = @import("std");
const stats = @import("stats.zig");
/// A compact weak handle for an IndexPool element type.
///
/// The zero value is always invalid. `T` gives handles compile-time element
/// type safety. Handles do not encode runtime pool identity: the owner must not
/// use a handle with a different IndexPool instance of the same element type.
pub fn TypedHandle(comptime T: type) type {
return packed struct(u32) {
index: u18 = 0,
generation: u14 = 0,
pub const _static = T;
pub const invalid: @This() = .{};
pub fn eql(self: @This(), other: @This()) bool {
return self.index == other.index and
self.generation == other.generation;
}
/// True when the handle is not the zero value. Handles minted by
/// IndexPool always carry a non-zero generation (fresh slots start at
/// 1 and reused slots keep their bumped generation), so the zero
/// value can never address a live element.
pub fn isValid(self: @This()) bool {
return @as(u32, @bitCast(self)) != 0;
}
/// The raw encoding, suitable as a hash-map key.
pub fn hash(self: @This()) u32 {
return @bitCast(self);
}
/// Implements the std.Io.Writer format interface so a handle can be
/// printed with `{f}` in format strings.
pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {
try writer.print("Handle({d},{d})", .{ self.index, self.generation });
}
};
}
/// A dense value pool with weak, generation-checked handles.
///
/// Values are stored densely and removed with swap-remove. Handles address a
/// separate slot table, so moving a dense value does not change its handle.
/// Pointers and slices returned by this type are invalidated by `new`,
/// `destroy`, `releaseAllFreeSlots`, or `deinit`.
///
/// The pool owns its backing allocations but does not call cleanup methods on
/// `T`. `destroy` returns the removed value so its caller can release any
/// resources owned by that value.
///
/// Handles belong to one pool instance. `releaseAllFreeSlots` is a full epoch
/// boundary: callers must discard every handle, including stale handles,
/// before calling it because the released generation history cannot be kept.
///
/// This type is not thread-safe.
pub fn IndexPool(comptime T: type) type {
return struct {
const Self = @This();
pub const SlotIndex = u18;
pub const Generation = u14;
const Slot = struct {
denseIndex: ?SlotIndex,
generation: Generation,
};
allocator: std.mem.Allocator,
dense: std.ArrayList(T) = .empty,
denseSlots: std.ArrayList(SlotIndex) = .empty,
slots: std.ArrayList(Slot) = .empty,
freeSlots: std.ArrayList(SlotIndex) = .empty,
pub const Handle = TypedHandle(T);
pub const maxSlotCount: usize = @as(usize, std.math.maxInt(SlotIndex)) + 1;
pub const CapacityError = std.mem.Allocator.Error || error{PoolFull};
pub fn init(allocator: std.mem.Allocator) Self {
return .{
.allocator = allocator,
};
}
/// Initializes a pool with capacity for `capacity` live or free slots.
/// The free list is reserved alongside the other storage, ensuring
/// that `destroy` never allocates.
pub fn initCapacity(allocator: std.mem.Allocator, capacity: usize) CapacityError!Self {
var self = init(allocator);
errdefer self.deinit();
try self.ensureTotalCapacity(capacity);
return self;
}
/// Reserves all dense, slot, and free-list storage.
pub fn ensureTotalCapacity(self: *Self, capacity: usize) CapacityError!void {
if (capacity > maxSlotCount) return error.PoolFull;
try self.dense.ensureTotalCapacity(self.allocator, capacity);
try self.denseSlots.ensureTotalCapacity(self.allocator, capacity);
try self.slots.ensureTotalCapacity(self.allocator, capacity);
try self.freeSlots.ensureTotalCapacity(self.allocator, capacity);
}
/// Returns a handle for a physical slot index when that slot is live.
pub fn indexToHandle(self: *const Self, index: usize) ?Handle {
if (index >= self.slots.items.len) return null;
const slot = self.slots.items[index];
if (slot.denseIndex == null) return null;
return .{
.index = @intCast(index),
.generation = slot.generation,
};
}
/// Returns the handle associated with a dense iteration index.
pub fn handleAtDenseIndex(self: *const Self, denseIndex: usize) ?Handle {
if (denseIndex >= self.denseSlots.items.len) return null;
return self.indexToHandle(self.denseSlots.items[denseIndex]);
}
/// Number of live values.
pub fn count(self: *const Self) usize {
return self.dense.items.len;
}
/// Number of allocated handle slots, including free and retired slots.
pub fn slotCount(self: *const Self) usize {
return self.slots.items.len;
}
/// Number of slots available for immediate allocation-free reuse.
pub fn freeCount(self: *const Self) usize {
return self.freeSlots.items.len;
}
pub fn getStatistics(self: *const Self) stats.PoolStatistics {
return .{
.statName = "IndexPool",
.instanceCount = self.count(),
.memoryReserved = self.dense.capacity * @sizeOf(T) +
self.denseSlots.capacity * @sizeOf(SlotIndex) +
self.slots.capacity * @sizeOf(Slot) +
self.freeSlots.capacity * @sizeOf(SlotIndex),
.memoryUsed = self.dense.items.len * @sizeOf(T) +
self.denseSlots.items.len * @sizeOf(SlotIndex) +
self.slots.items.len * @sizeOf(Slot) +
self.freeSlots.items.len * @sizeOf(SlotIndex),
};
}
/// Dense read-only iteration. Invalidated by any mutating pool method.
pub fn items(self: *const Self) []const T {
return self.dense.items;
}
/// Dense mutable iteration. Invalidated by any other mutating pool method.
pub fn itemsMut(self: *Self) []T {
return self.dense.items;
}
pub fn new(self: *Self, initVal: T) CapacityError!Handle {
if (self.freeSlots.items.len != 0) {
const slotIndex = self.freeSlots.pop().?;
const denseIndex: SlotIndex = @intCast(self.dense.items.len);
const slot = &self.slots.items[slotIndex];
std.debug.assert(slot.denseIndex == null);
std.debug.assert(slot.generation != 0);
std.debug.assert(self.dense.items.len < self.dense.capacity);
std.debug.assert(self.denseSlots.items.len < self.denseSlots.capacity);
self.dense.appendAssumeCapacity(initVal);
self.denseSlots.appendAssumeCapacity(slotIndex);
slot.denseIndex = denseIndex;
return .{
.index = slotIndex,
.generation = slot.generation,
};
}
if (self.slots.items.len == maxSlotCount) return error.PoolFull;
const newSlotCount = self.slots.items.len + 1;
try self.ensureTotalCapacity(newSlotCount);
const slotIndex: SlotIndex = @intCast(self.slots.items.len);
const denseIndex: SlotIndex = @intCast(self.dense.items.len);
const initialGeneration: Generation = 1;
self.dense.appendAssumeCapacity(initVal);
self.denseSlots.appendAssumeCapacity(slotIndex);
self.slots.appendAssumeCapacity(.{
.denseIndex = denseIndex,
.generation = initialGeneration,
});
return .{
.index = slotIndex,
.generation = initialGeneration,
};
}
pub fn isValid(self: *const Self, handle: Handle) bool {
if (handle.generation == 0) return false;
if (handle.index >= self.slots.items.len) return false;
const slot = self.slots.items[handle.index];
return slot.denseIndex != null and slot.generation == handle.generation;
}
pub fn get(self: *Self, handle: Handle) ?*T {
if (!self.isValid(handle)) return null;
const denseIndex = self.slots.items[handle.index].denseIndex.?;
return &self.dense.items[denseIndex];
}
pub fn getRead(self: *const Self, handle: Handle) ?*const T {
if (!self.isValid(handle)) return null;
const denseIndex = self.slots.items[handle.index].denseIndex.?;
return &self.dense.items[denseIndex];
}
/// Removes a live value and returns it to the caller.
///
/// Invalid, stale, and duplicate handles return null without changing
/// the pool. Removal is allocation-free because free-list capacity is
/// reserved whenever slot capacity grows.
pub fn destroy(self: *Self, handle: Handle) ?T {
if (!self.isValid(handle)) return null;
const slot = &self.slots.items[handle.index];
const denseIndex = slot.denseIndex.?;
const removedValue = self.dense.swapRemove(denseIndex);
const removedSlot = self.denseSlots.swapRemove(denseIndex);
std.debug.assert(removedSlot == handle.index);
if (denseIndex < self.dense.items.len) {
const movedSlot = self.denseSlots.items[denseIndex];
self.slots.items[movedSlot].denseIndex = denseIndex;
}
slot.denseIndex = null;
if (slot.generation == std.math.maxInt(Generation)) {
// Retire this slot permanently rather than wrapping and making
// an old handle valid again.
} else {
slot.generation += 1;
std.debug.assert(self.freeSlots.items.len < self.freeSlots.capacity);
self.freeSlots.appendAssumeCapacity(handle.index);
}
return removedValue;
}
/// Fully releases pool storage when there are no live values.
///
/// This is a full epoch boundary. Every handle associated with this
/// pool must be discarded before calling it; rebuilding the pool can
/// reuse the same index and generation values. Returns false when
/// values are still live or there is no allocation to release.
pub fn releaseAllFreeSlots(self: *Self) bool {
if (self.dense.items.len != 0) return false;
const hadStorage = self.dense.capacity != 0 or
self.denseSlots.capacity != 0 or
self.slots.capacity != 0 or
self.freeSlots.capacity != 0;
if (!hadStorage) return false;
self.dense.clearAndFree(self.allocator);
self.denseSlots.clearAndFree(self.allocator);
self.slots.clearAndFree(self.allocator);
self.freeSlots.clearAndFree(self.allocator);
return true;
}
pub fn deinit(self: *Self) void {
self.dense.deinit(self.allocator);
self.denseSlots.deinit(self.allocator);
self.slots.deinit(self.allocator);
self.freeSlots.deinit(self.allocator);
self.* = undefined;
}
};
}
const TestValue = struct {
id: u32,
};
const TestPool = IndexPool(TestValue);
test "index pool handles are typed and zero-invalid" {
try std.testing.expect(TypedHandle(u32) != TypedHandle(u64));
try std.testing.expectEqual(@as(usize, 4), @sizeOf(TestPool.Handle));
try std.testing.expectEqual(@as(usize, 1) << 18, TestPool.maxSlotCount);
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
try std.testing.expect(!pool.isValid(.{}));
const handle = try pool.new(.{ .id = 42 });
try std.testing.expect(handle.generation != 0);
try std.testing.expect(pool.isValid(handle));
try std.testing.expectEqual(@as(u32, 42), pool.get(handle).?.id);
}
test "index pool rejects stale and duplicate destruction" {
var first = TestPool.init(std.testing.allocator);
defer first.deinit();
const original = try first.new(.{ .id = 1 });
const removed = first.destroy(original).?;
try std.testing.expectEqual(@as(u32, 1), removed.id);
try std.testing.expect(!first.isValid(original));
try std.testing.expect(first.destroy(original) == null);
const replacement = try first.new(.{ .id = 2 });
try std.testing.expectEqual(original.index, replacement.index);
try std.testing.expect(original.generation != replacement.generation);
try std.testing.expect(first.destroy(original) == null);
try std.testing.expectEqual(@as(u32, 2), first.get(replacement).?.id);
}
test "index pool keeps values dense while handles remain stable" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
const first = try pool.new(.{ .id = 1 });
const middle = try pool.new(.{ .id = 2 });
const last = try pool.new(.{ .id = 3 });
_ = pool.destroy(middle).?;
try std.testing.expectEqual(@as(usize, 2), pool.count());
try std.testing.expectEqualSlices(TestValue, &.{ .{ .id = 1 }, .{ .id = 3 } }, pool.items());
try std.testing.expectEqual(@as(u32, 1), pool.get(first).?.id);
try std.testing.expectEqual(@as(u32, 3), pool.get(last).?.id);
try std.testing.expect(pool.indexToHandle(middle.index) == null);
try std.testing.expect(pool.indexToHandle(last.index).?.eql(last));
try std.testing.expect(pool.handleAtDenseIndex(1).?.eql(last));
}
test "index pool retires slots instead of wrapping generations" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
var handle = try pool.new(.{ .id = 1 });
var expectedGeneration: u32 = 1;
while (expectedGeneration < std.math.maxInt(TestPool.Generation)) : (expectedGeneration += 1) {
_ = pool.destroy(handle).?;
handle = try pool.new(.{ .id = 1 });
try std.testing.expectEqual(@as(TestPool.Generation, @intCast(expectedGeneration + 1)), handle.generation);
try std.testing.expectEqual(@as(TestPool.SlotIndex, 0), handle.index);
}
const retiredHandle = handle;
_ = pool.destroy(retiredHandle).?;
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
const next = try pool.new(.{ .id = 2 });
try std.testing.expectEqual(@as(TestPool.SlotIndex, 1), next.index);
try std.testing.expect(!pool.isValid(retiredHandle));
}
test "index pool reserves its free list and can release an empty pool" {
var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var pool = try TestPool.initCapacity(allocatorState.allocator(), 8);
defer pool.deinit();
try std.testing.expect(pool.dense.capacity >= 8);
try std.testing.expect(pool.denseSlots.capacity >= 8);
try std.testing.expect(pool.slots.capacity >= 8);
try std.testing.expect(pool.freeSlots.capacity >= 8);
const allocationsAfterReserve = allocatorState.allocations;
var handles: [8]TestPool.Handle = undefined;
for (&handles, 0..) |*handle, i| {
handle.* = try pool.new(.{ .id = @intCast(i) });
}
try std.testing.expect(!pool.releaseAllFreeSlots());
for (handles) |handle| {
_ = pool.destroy(handle).?;
}
try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations);
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(pool.slotCount(), pool.freeCount());
try std.testing.expect(pool.releaseAllFreeSlots());
try std.testing.expectEqual(@as(usize, 0), pool.dense.capacity);
try std.testing.expectEqual(@as(usize, 0), pool.denseSlots.capacity);
try std.testing.expectEqual(@as(usize, 0), pool.slots.capacity);
try std.testing.expectEqual(@as(usize, 0), pool.freeSlots.capacity);
const rebuilt = try pool.new(.{ .id = 99 });
try std.testing.expectEqual(@as(TestPool.SlotIndex, 0), rebuilt.index);
try std.testing.expectEqual(@as(TestPool.Generation, 1), rebuilt.generation);
}
test "index pool reports growth allocation failures" {
for (0..4) |failIndex| {
var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{
.fail_index = failIndex,
});
var pool = TestPool.init(failingState.allocator());
defer pool.deinit();
try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 }));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.slotCount());
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
}
}
test "index pool rejects capacity beyond its handle index range" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
try std.testing.expectError(error.PoolFull, pool.ensureTotalCapacity(TestPool.maxSlotCount + 1));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.slotCount());
}

View File

@ -0,0 +1,14 @@
const std = @import("std");
// TODO:
//
// This one is not quite finished yet.
//
// The idea for this one is to efficently map one
// arbitrary set of integers to another set of integers.
pub fn IntMapperUnmanaged(comptime IntType: type) type {
return struct {
capacity: usize,
smallMap: []IntType,
};
}

View File

@ -0,0 +1,136 @@
pub fn MakeInterface(comptime vtable_declname: []const u8, comptime VTableType: type) type {
return struct {
pub const VTableDeclName = vtable_declname;
pub const VTable = VTableType;
pub fn Implement(comptime T: type) VTableType {
return VTableType.Implement(T);
}
};
}
pub fn Reference(comptime Interface: type) type {
return struct {
ptr: *anyopaque,
vtable: Interface.VTable,
};
}
pub inline fn refFromPtr(comptime Interface: type, ptr: anytype) Reference(Interface) {
return .{
.ptr = @ptrCast(ptr),
.vtable = @field(@TypeOf(ptr.*), Interface.VTableDeclName),
};
}
test "simple" {
const std = @import("std");
const TestOtherInterface = MakeInterface("TestOtherInterfaceVTable", struct {
testOtherfn: *const fn (*anyopaque, f64, f64) f64,
pub fn Implement(comptime T: type) @This() {
const Wrap = struct {
pub fn testOtherfn(p: *anyopaque, a: f64, b: f64) f64 {
const ptr: *T = @ptrCast(@alignCast(p));
return ptr.testOtherfn(a, b);
}
};
inline for (@typeInfo(Wrap).@"struct".decls) |d| {
if (!@hasDecl(T, d.name)) {
@compileError(@typeName(T) ++ " is missing implementation of func " ++ d.name);
}
}
return .{
.testOtherfn = Wrap.testOtherfn,
};
}
});
const TestInterface = MakeInterface("TestInterfaceVTable", struct {
testfn1: *const fn (*anyopaque, f64, f64) f64,
testfn2: *const fn (*anyopaque, []const u8) void,
pub fn Implement(comptime T: type) @This() {
const Wrap = struct {
pub fn testfn1(p: *anyopaque, a: f64, b: f64) f64 {
const ptr: *T = @ptrCast(@alignCast(p));
return ptr.testfn1(a, b);
}
pub fn testfn2(p: *anyopaque, msg: []const u8) void {
const ptr: *T = @ptrCast(@alignCast(p));
ptr.testfn2(msg);
}
};
inline for (@typeInfo(Wrap).@"struct".decls) |d| {
if (!@hasDecl(T, d.name)) {
@compileError(@typeName(T) ++ " is missing implementation of func " ++ d.name);
}
}
return .{
.testfn1 = Wrap.testfn1,
.testfn2 = Wrap.testfn2,
};
}
});
const Test1 = struct {
name: []const u8,
pub const TestInterfaceVTable = TestInterface.Implement(@This());
pub const TestOtherInterfaceVTable = TestOtherInterface.Implement(@This());
// gathered into TestInterfaceVTable
pub fn testfn1(self: *@This(), a: f64, b: f64) f64 {
std.debug.print("{s}: a + b == {d}\n", .{ self.name, a + b });
return a + b;
}
// gathered into TestInterfaceVTable
pub fn testfn2(self: *@This(), msg: []const u8) void {
std.debug.print("{s}: msg: {s}\n", .{ self.name, msg });
}
// gathered into TestOtherInterfaceVTable
pub fn testOtherfn(self: *@This(), a: f64, b: f64) f64 {
_ = self;
std.debug.print(">: a - b == {d}\n", .{a - b});
return a - b;
}
};
const Test2 = struct {
name: []const u8,
pub const TestInterfaceVTable = TestInterface.VTable.Implement(@This());
pub fn testfn1(self: *@This(), a: f64, b: f64) f64 {
std.debug.print("2>{s}: a * b == {d}\n", .{ self.name, a * b });
return a * b;
}
pub fn testfn2(self: *@This(), msg: []const u8) void {
std.debug.print("2>{s}: msg: {s}\n", .{ self.name, msg });
}
};
var t1 = Test1{ .name = "test1" };
var t2 = Test2{ .name = "test2" };
const refs = [_]Reference(TestInterface){
refFromPtr(TestInterface, &t1),
refFromPtr(TestInterface, &t2),
};
std.debug.print("\n", .{});
for (refs) |r| {
_ = r.vtable.testfn1(r.ptr, 12.0, 24.0);
}
const ref = refFromPtr(TestOtherInterface, &t1);
_ = ref.vtable.testOtherfn(ref.ptr, 12.0, 42.0);
}

View File

@ -0,0 +1,688 @@
const std = @import("std");
pub const zm = @import("zmath.zig");
const math = std.math;
// vector versions.
pub const f32x4 = @Vector(4, f32); // __m128_int
pub const f32x8 = @Vector(8, f32); // __m256_int
pub const f32x16 = @Vector(16, f32); // __m512_int
pub const f32x4_zero = std.mem.zeroes(@Vector(4, f32));
pub const f32x8_zero = std.mem.zeroes(@Vector(8, f32));
pub const f32x16_zero = std.mem.zeroes(@Vector(16, f32));
pub const Rayf = RayType(Vectorf);
pub const PlaneBasisf = struct {
u_axis: Vectorf,
v_axis: Vectorf,
};
// creates a translation matrix 4x4
pub const identity = zm.identity;
pub fn matToScalef(mat: anytype) Vectorf {
const x = Vectorf.new(mat[0][0], mat[0][1], mat[0][2]).length();
const y = Vectorf.new(mat[1][0], mat[1][1], mat[1][2]).length();
const z = Vectorf.new(mat[2][0], mat[2][1], mat[2][2]).length();
return Vectorf.new(x, y, z);
}
/// Builds a stable orthonormal basis for the plane described by `normal`.
pub fn planeBasisFromNormal(normal: Vectorf) PlaneBasisf {
const n = if (normal.length() > 0.0001) normal.normalize() else Vectorf.Forward;
const reference = if (@abs(n.dot(Vectorf.Up)) < 0.94) Vectorf.Up else Vectorf.Right;
var u_axis = reference.cross(n);
if (u_axis.length() <= 0.0001) u_axis = Vectorf.Right;
u_axis = u_axis.normalize();
var v_axis = n.cross(u_axis);
if (v_axis.length() <= 0.0001) v_axis = Vectorf.Up;
v_axis = v_axis.normalize();
return .{
.u_axis = u_axis,
.v_axis = v_axis,
};
}
/// Returns the component of `vector` perpendicular to a normalized axis.
pub fn vectorRejectNormalized(vector: Vectorf, axis_normalized: Vectorf) Vectorf {
return vector.sub(axis_normalized.fmul(vector.dot(axis_normalized)));
}
pub fn RayType(comptime T: type) type {
return struct {
start: T,
dir: T,
};
}
pub fn clamp(x: anytype, min: anytype, max: anytype) @TypeOf(x) {
if (x < min)
return min;
if (x > max)
return max;
return x;
}
pub fn matFromEulerAngles(x: f32, y: f32, z: f32) Mat {
return zm.matFromRollPitchYaw(y, z, x);
}
pub fn Radians(comptime T: type) type {
return struct {
value: T,
pub fn fromDegrees(f: anytype) @This() {
return .{ .value = f };
}
};
}
pub fn radians(f: anytype) @TypeOf(f) {
return f * math.pi / 180.0;
}
pub fn fabs(x: anytype) @TypeOf(x) {
if (x < 0)
return -x;
return x;
}
pub fn Vector2Type(comptime T: type, comptime typeName: []const u8) type {
return extern struct {
x: T = 0,
y: T = 0,
pub const VectorTypeName = typeName;
pub const ones = @This(){ .x = 1, .y = 1 };
pub const zeroes = @This(){ .x = 0, .y = 0 };
pub const Ones = @This(){ .x = 1, .y = 1 };
pub const Zeroes = @This(){ .x = 0, .y = 0 };
pub inline fn new(x: T, y: T) @This() {
return .{
.x = x,
.y = y,
};
}
pub inline fn add(self: @This(), other: @This()) @This() {
return .{
.x = self.x + other.x,
.y = self.y + other.y,
};
}
pub inline fn sub(self: @This(), other: @This()) @This() {
return .{
.x = self.x - other.x,
.y = self.y - other.y,
};
}
pub inline fn vmul(self: @This(), other: @This()) @This() {
return .{
.x = self.x * other.x,
.y = self.y * other.y,
};
}
pub inline fn divFloor(self: @This(), other: T) @This() {
return .{
.x = @divFloor(self.x, other),
.y = @divFloor(self.y, other),
};
}
pub inline fn fmul(self: @This(), other: T) @This() {
return .{
.x = self.x * other,
.y = self.y * other,
};
}
pub inline fn dot(self: @This(), other: @This()) T {
return self.x * other.x + self.y * other.y;
}
pub inline fn equals(self: @This(), other: @This()) bool {
return self.x == other.x and self.y == other.y;
}
pub inline fn length(self: @This()) T {
return std.math.sqrt(self.x * self.x + self.y * self.y);
}
pub inline fn swizzleYX(self: @This()) @This() {
return .{ .x = self.y, .y = self.x };
}
pub inline fn normalize(self: @This()) @This() {
if (fabs(self.x) <= 0.0001 and fabs(self.y) <= 0.0001) {
return .{ .x = 0, .y = 0 };
}
const len = std.math.sqrt(self.x * self.x + self.y * self.y);
if (len < 0.00001)
return .{ .x = 0, .y = 0 };
return .{
.x = self.x / len,
.y = self.y / len,
};
}
pub inline fn negate(self: @This()) @This() {
return .{ .x = -self.x, .y = self.y };
}
pub inline fn cross(self: @This(), other: @This()) T {
return self.x * other.y - self.y * other.x;
}
pub inline fn removeComponent(self: @This(), other: @This()) @This() {
return self.sub(other.fmul(self.dot(other)));
}
pub inline fn from(o: anytype) @This() {
const OType: std.builtin.Type = @typeInfo(@TypeOf(o.x));
switch (@typeInfo(T)) {
.int => {
switch (OType) {
.int => {
// convert integer into integer
return .{
.x = @intCast(o.x),
.y = @intCast(o.y),
};
},
.float => {
// convert float into float
return .{
.x = @intFromFloat(o.x),
.y = @intFromFloat(o.y),
};
},
else => {
@compileError("Invalid vector type conversion");
},
}
},
.float => {
switch (OType) {
.int => {
// convert integer into float
return .{
.x = @floatFromInt(o.x),
.y = @floatFromInt(o.y),
};
},
.float => {
// convert float
return .{
.x = @floatCast(o.x),
.y = @floatCast(o.y),
};
},
else => {
// convert float into float
@compileError("Invalid vector type conversion");
},
}
},
else => {
@compileError("Invalid vector type conversion");
},
}
@compileError("Invalid vector conversion");
}
};
}
pub fn Vector3Type(comptime T: type, comptime typeName: []const u8) type {
return extern struct {
x: T = 0,
y: T = 0,
z: T = 0,
pub const VectorTypeName = typeName;
pub const ones = @This(){ .x = 1.0, .y = 1.0, .z = 1.0 };
pub const zeroes = @This(){ .x = 0, .y = 0, .z = 0.0 };
pub const Ones = @This(){ .x = 1, .y = 1, .z = 1 };
pub const Zeroes = @This(){ .x = 0, .y = 0, .z = 0 };
pub const Up = @This(){ .y = 1 };
pub const Right = @This(){ .x = 1 };
pub const Forward = @This(){ .z = 1 };
pub inline fn new(x: T, y: T, z: T) @This() {
return .{
.x = x,
.y = y,
.z = z,
};
}
pub inline fn fromInt(t: anytype) @This() {
return .{ .x = t, .y = t, .z = t };
}
pub inline fn splat(t: anytype) @This() {
return .{ .x = t, .y = t, .z = t };
}
// easing functions
pub inline fn drainToZero(self: @This(), o: anytype) @This() {
return self.drain(o, Zeroes);
}
pub inline fn drain(self: @This(), o: anytype, target: anytype) @This() {
return .{
.x = drainElement(self.x, o.x, target.x),
.y = drainElement(self.y, o.y, target.y),
.z = drainElement(self.z, o.z, target.z),
};
}
inline fn drainElement(a: anytype, v: anytype, t: anytype) @TypeOf(a) {
if (a > t) {
return @max(t, a - v);
} else {
return @min(t, a + v);
}
}
// array functions.
pub inline fn toArr3(self: @This()) [3]T {
return .{ self.x, self.y, self.z };
}
pub inline fn fromArr3(v: [3]f32) @This() {
return .{ .x = v[0], .y = v[1], .z = v[2] };
}
pub inline fn toZm(self: @This()) zm.Vec {
return .{ self.x, self.y, self.z, 1.0 };
}
pub inline fn fromZm(vec: zm.Vec) @This() {
return @This().new(vec[0], vec[1], vec[2]);
}
pub inline fn add(self: @This(), other: @This()) @This() {
return .{
.x = self.x + other.x,
.y = self.y + other.y,
.z = self.z + other.z,
};
}
pub inline fn sub(self: @This(), other: @This()) @This() {
return .{
.x = self.x - other.x,
.y = self.y - other.y,
.z = self.z - other.z,
};
}
pub inline fn vmul(self: @This(), other: @This()) @This() {
return .{
.x = self.x * other.x,
.y = self.y * other.y,
.z = self.z * other.z,
};
}
pub inline fn fmul(self: @This(), other: T) @This() {
return .{
.x = self.x * other,
.y = self.y * other,
.z = self.z * other,
};
}
pub inline fn dot(self: @This(), other: @This()) T {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
pub inline fn equals(self: @This(), other: @This()) bool {
return self.x == other.x and self.y == self.y and self.z == self.z;
}
pub inline fn eql(self: @This(), other: @This()) bool {
return self.x == other.x and self.y == self.y and self.z == self.z;
}
pub inline fn length(self: @This()) T {
return std.math.sqrt(self.x * self.x + self.z * self.z + self.y * self.y);
}
pub inline fn swizzleYZX(self: @This()) @This() {
return .{ .x = self.y, .y = self.z, .z = self.x };
}
pub inline fn swizzleYXZ(self: @This()) @This() {
return .{ .x = self.y, .y = self.x, .z = self.z };
}
pub inline fn swizzleZXY(self: @This()) @This() {
return .{ .x = self.z, .y = self.x, .z = self.y };
}
pub inline fn swizzleZYX(self: @This()) @This() {
return .{ .x = self.z, .y = self.y, .z = self.x };
}
pub inline fn swizzleXZY(self: @This()) @This() {
return .{ .x = self.x, .y = self.z, .z = self.y };
}
pub inline fn lengthXZ(self: @This()) T {
return std.math.sqrt(self.x * self.x + self.z * self.z);
}
pub inline fn normalize(self: @This()) @This() {
if (fabs(self.x) <= 0.0001 and fabs(self.y) <= 0.0001 and fabs(self.z) <= 0.0001) {
return .{ .x = 0, .y = 0, .z = 0 };
}
const len = std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
if (len < 0.00001)
return .{ .x = 0, .y = 0, .z = 0 };
return .{
.x = self.x / len,
.y = self.y / len,
.z = self.z / len,
};
}
pub inline fn fromArray(o: anytype) @This() {
return .{
.x = o[0],
.y = o[1],
.z = o[2],
};
}
pub inline fn clampAllAbs(self: @This(), abs: anytype) @This() {
return .{
.x = std.math.clamp(self.x, -abs, abs),
.y = std.math.clamp(self.y, -abs, abs),
.z = std.math.clamp(self.z, -abs, abs),
};
}
pub inline fn cross(self: @This(), other: @This()) @This() {
return .{
.x = self.y * other.z - self.z * other.y,
.y = self.z * other.x - self.x * other.z,
.z = self.x * other.y - self.y * other.x,
};
}
pub fn lerp(self: @This(), other: @This(), alpha: anytype) @This() {
return .{
.x = std.math.lerp(self.x, other.x, alpha),
.y = std.math.lerp(self.y, other.y, alpha),
.z = std.math.lerp(self.z, other.z, alpha),
};
}
pub inline fn clampAll(self: @This(), lower: anytype, upper: anytype) @This() {
return .{
.x = std.math.clamp(self.x, -lower, upper),
.y = std.math.clamp(self.y, -lower, upper),
.z = std.math.clamp(self.z, -lower, upper),
};
}
pub inline fn from(o: anytype) @This() {
const OType = @typeInfo(@TypeOf(o.x));
switch (@typeInfo(T)) {
.int => {
switch (OType) {
.int => {
// convert integer into integer
return .{
.x = @intCast(o.x),
.y = @intCast(o.y),
.z = @intCast(o.z),
};
},
.float => {
// convert float into float
return .{
.x = @intFromFloat(o.x),
.y = @intFromFloat(o.y),
.z = @intFromFloat(o.z),
};
},
else => {
@compileError("Invalid vector type conversion");
},
}
},
.float => {
switch (OType) {
.int, .comptime_int => {
// convert integer into float
return .{
.x = @floatFromInt(o.x),
.y = @floatFromInt(o.y),
.z = @floatFromInt(o.z),
};
},
.float, .comptime_float => {
// convert float
return .{
.x = @floatCast(o.x),
.y = @floatCast(o.y),
.z = @floatCast(o.z),
};
},
else => {
// convert float into float
@compileError("Invalid vector type conversion");
},
}
},
else => {
@compileError("Invalid vector type conversion");
},
}
@compileError("Invalid vector conversion");
}
};
}
pub fn Vector4Type(comptime T: type) type {
return extern struct {
x: T = 0,
y: T = 0,
z: T = 0,
w: T = 0,
pub const Ones = @This(){ .x = 1, .y = 1, .z = 1 };
pub const Zeroes = @This(){ .x = 0, .y = 0, .z = 0 };
pub const ones = @This(){ .x = 1, .y = 1, .z = 1 };
pub const zero = @This(){ .x = 0, .y = 0, .z = 0 };
pub inline fn from(o: anytype) @This() {
return .{ .x = o.x, .y = o.y, .z = o.z, .w = o.w };
}
pub inline fn new(x: T, y: T, z: T, w: T) @This() {
return .{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
pub inline fn add(self: @This(), other: @This()) @This() {
return .{
.x = self.x + other.x,
.y = self.y + other.y,
.z = self.z + other.z,
.w = self.w + other.w,
};
}
pub inline fn sub(self: @This(), other: @This()) @This() {
return .{
.x = self.x - other.x,
.y = self.y - other.y,
.z = self.z - other.z,
.w = self.w - other.w,
};
}
pub inline fn normalize(self: @This()) @This() {
const len = std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w);
return .{
.x = self.x / len,
.y = self.y / len,
.z = self.z / len,
.w = self.w / len,
};
}
};
}
pub const Vector4 = Vector4Type(f64);
pub const Vector4f = Vector4Type(f32);
pub const Vector = Vector3Type(f64, "Vector");
pub const Vectorf = Vector3Type(f32, "Vectorf");
pub const Vector2f = Vector2Type(f32, "Vector2f");
pub const Vector2 = Vector2Type(f64, "Vector2");
pub const Vector2i = Vector2Type(i32, "Vector2i");
pub const Vector2c = Vector2Type(c_int, "Vector2c");
pub const Vector2u = Vector2Type(u32, "Vector2u");
pub const Vector2l = Vector2Type(i64, "Vector2l");
pub const EulerAngles = Vectorf;
pub const Quat = zm.Quat;
pub const Mat = zm.Mat;
pub const Transform = zm.Mat;
pub fn matGetPosition(m: Mat) Vectorf {
const vec: Vectorf = .{};
return Vectorf.fromZm(zm.mul(vec.toZm(), m));
}
pub fn matToRotation(m: Mat) Rotation {
const r: Rotation = .{ .quat = zm.matToQuat(m) };
return r;
}
pub const Rotation = struct {
quat: Quat = zm.qidentity(),
pub fn init() @This() {
return .{};
}
pub fn isIdentity(self: @This()) bool {
return self.quat[0] == 0.0 and self.quat[1] == 0.0 and
self.quat[2] == 0.0 and self.quat[3] == 1.0;
}
pub fn add(self: @This(), other: @This()) Rotation {
const m1 = zm.quatToMat(self.quat);
const m2 = zm.quatToMat(other.quat);
const r = zm.mul(m1, m2);
return .{ .quat = zm.matToQuat(r) };
}
pub fn eulerX(o: f32) @This() {
return .{
.quat = zm.matToQuat(zm.rotationX((o))),
};
}
pub fn eulerY(o: f32) @This() {
return .{
.quat = zm.matToQuat(zm.rotationY((o))),
};
}
pub fn eulerZ(o: f32) @This() {
return .{
.quat = zm.matToQuat(zm.rotationZ((o))),
};
}
pub fn up(self: @This()) Vectorf {
return self.rotateVector(Vectorf.Up);
}
pub fn forward(self: @This()) Vectorf {
return self.rotateVector(Vectorf.Forward);
}
pub fn right(self: @This()) Vectorf {
return self.rotateVector(Vectorf.Right);
}
pub fn rotateVector(self: @This(), other: Vectorf) Vectorf {
return Vectorf.fromZm(
zm.mul(
other.toZm(),
zm.quatToMat(self.quat),
),
);
}
};
pub fn lerp(a: f32, b: f32, t: f32) f32 {
return a + t * (b - a);
}
pub fn simdVec4ToVec(vec: zm.Vec) Vector4f {
return .{
.x = vec[0],
.y = vec[1],
.z = vec[2],
.w = vec[3],
};
}
pub fn easeLinear(c: f32, t: f32, dt: f64, rate: f32) f32 {
const d = rate * @as(f32, @floatCast(dt));
if (c > t) {
return @max(c - d, t);
} else if (c < t) {
return @min(c + d, t);
} else {
return t;
}
}
pub fn rollingAverage(average: *f64, newValue: f64, sampleCount: f64) void {
average.* = average.* - (average.* / sampleCount) + newValue / sampleCount;
}
pub fn finite(value: f32) bool {
return !math.isNan(value) and !math.isInf(value);
}
pub fn validVector(value: Vectorf) bool {
return finite(value.x) and finite(value.y) and finite(value.z);
}
pub fn validRotation(value: Rotation) bool {
inline for (0..4) |index| if (!finite(value.quat[index])) return false;
return true;
}

View File

@ -0,0 +1,306 @@
const std = @import("std");
const stats = @import("stats.zig");
const paged_vector = @import("paged-vector.zig");
const builtin = @import("builtin");
const PagedVectorAdvanced = paged_vector.PagedVectorAdvanced;
pub const NameRegistryStatus = enum {
Ok,
OutOfMemory,
};
pub const NameInvalid: Name = .{ .index = 0 };
const NameInvalidComptimeString = "Invalid";
// trying out a names scheme similar in vein to unreal engine's FNames
pub const NameRegistry = struct {
allocator: std.mem.Allocator,
io_context: std.Io,
map: std.StringHashMapUnmanaged(u32), // todo.. this can be replaced with a specialized hashmap
pagedVector: PagedVectorAdvanced([]const u8, 1024),
stringArena: std.heap.ArenaAllocator,
mutex: std.Io.Mutex = .init,
// with this system errors should be nonexistent
// as a result I downgrade all errors into this error status field.
// I think the enhanced ergonomics of being able to use names ubiquitously is worth losing the
// immediate handling of the trace.
//
// usage of names should be null checked anyway.
errorStatus: NameRegistryStatus = .Ok,
pub fn init(allocator: std.mem.Allocator, io_context: std.Io) !@This() {
var self = @This(){
.allocator = allocator,
.io_context = io_context,
.stringArena = std.heap.ArenaAllocator.init(allocator),
.map = .empty,
.pagedVector = try PagedVectorAdvanced([]const u8, 1024).init(allocator),
};
_ = self.InstallNameInner(NameInvalidComptimeString, false);
return self;
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
pub fn count(self: @This()) u32 {
return @intCast(self.pagedVector.len());
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
// per-entry cost of the string->index hashmap (key + value + metadata byte)
const mapEntryBytes = @sizeOf([]const u8) + @sizeOf(u32) + 1;
var stringBytes: usize = 0;
for (0..self.pagedVector.len()) |i| {
stringBytes += self.pagedVector.get(i).len;
}
const vectorStats = self.pagedVector.getStatistics();
return .{
.statName = "NameRegistry",
.instanceCount = self.count(),
.memoryReserved = vectorStats.memoryReserved +
self.stringArena.queryCapacity() +
self.map.capacity() * mapEntryBytes,
.memoryUsed = vectorStats.memoryUsed +
stringBytes +
self.map.count() * mapEntryBytes,
};
}
pub fn name(self: *@This(), nameString: []const u8) Name {
const index = self.InstallNameInner(nameString, true);
return .{
.index = index,
.string = self.pagedVector.get(index).*,
};
}
fn InstallNameInner(self: *@This(), nameString: []const u8, shouldCopy: bool) u32 {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
var newString = nameString;
// check if the string exists if it does just return it as a name.
if (self.map.get(newString)) |index| {
return index;
}
if (shouldCopy) {
var allocator = self.stringArena.allocator();
newString = allocator.dupe(u8, nameString) catch {
self.errorStatus = .OutOfMemory;
@panic("Out of memory during name operation");
};
}
// add to registry
const newIndex = @as(u32, @intCast(self.pagedVector.len()));
self.pagedVector.append(self.allocator, newString) catch {
self.errorStatus = .OutOfMemory;
@panic("Out of memory during name operation");
};
self.map.put(self.allocator, newString, newIndex) catch {
self.errorStatus = .OutOfMemory;
@panic("Out of memory during name operation");
};
return newIndex;
}
pub fn deinit(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
self.map.deinit(self.allocator);
self.pagedVector.deinit(self.allocator);
self.stringArena.deinit();
}
};
pub var gRegistry: *NameRegistry = undefined;
var registryCreated: bool = false;
var registryOwned: bool = false;
pub var gStringArena: std.heap.ArenaAllocator = undefined;
var testArenaActive: bool = false;
pub fn createNameRegistry(allocator: std.mem.Allocator, io_context: std.Io) !*NameRegistry {
if (!registryCreated) {
gRegistry = try allocator.create(NameRegistry);
gRegistry.* = try NameRegistry.init(allocator, io_context);
registryCreated = true;
registryOwned = true;
}
return gRegistry;
}
pub fn setNameRegistry(registry: *NameRegistry) void {
gRegistry = registry;
registryCreated = true;
registryOwned = false;
}
pub fn isReady() bool {
return registryCreated;
}
pub fn getRegistry() *NameRegistry {
// specifically in the case of unittests we can silently just initialize a temporary registry
if (builtin.is_test) {
if (!registryCreated) {
gStringArena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
testArenaActive = true;
// leaking here is fine? might piss off valgrind
_ = createNameRegistry(gStringArena.allocator(), std.testing.io) catch unreachable;
}
}
return gRegistry;
}
pub fn destroyNameRegistry() void {
if (!registryCreated) return;
if (registryOwned) {
var allocator = gRegistry.allocator;
gRegistry.deinit();
allocator.destroy(gRegistry);
}
if (testArenaActive) {
gStringArena.deinit();
testArenaActive = false;
}
registryCreated = false;
registryOwned = false;
}
// use this one when you want to be able to chain multiple declarations,
// otherwise DefineName is a bit nicer
pub fn ComptimeName(comptime s: []const u8) type {
return struct {
pub const string = s;
pub var name: Name = DefineName(string);
pub const copy: Name = DefineName(string);
};
}
pub fn DefineName(comptime string: []const u8) Name {
return Name.MakeComptime(string);
}
pub fn MakeName(string: []const u8) Name {
return Name.Make(string);
}
pub const Name = struct {
index: ?u32 = 0, // do not directly access
string: []const u8 = "Invalid", // do not directly access
pub fn MakeComptime(string: []const u8) @This() {
return .{ .index = null, .string = string };
}
pub fn Make(string: []const u8) @This() {
return getRegistry().name(string);
}
pub fn fromUtf8(string: []const u8) @This() {
return getRegistry().name(string);
}
pub fn handle(self: *@This()) u32 {
if (self.index == null) {
const index = getRegistry().InstallNameInner(self.string, false);
self.index = index;
}
return self.index.?;
}
pub fn utf8(self: *@This()) []const u8 {
// so nasty... and const-violating. but the ergonomics is so good...
if (self.index == null) {
// screw it.. i'll pay the cost of duplicating even comptime strings
const index = getRegistry().InstallNameInner(self.string, true);
self.index = index;
}
return getRegistry().pagedVector.get(self.index.?).*;
}
pub fn eql(self: *@This(), other: *@This()) bool {
if (self.index == null) {
const index = getRegistry().InstallNameInner(self.string, false);
const mutableThis = self;
mutableThis.*.index = index;
}
if (other.index == null) {
const index = getRegistry().InstallNameInner(self.string, false);
const mutableThis = self;
mutableThis.*.index = index;
}
return self.index == other.index;
}
};
pub fn StaticName(comptime N: []const u8) type {
return struct {
pub const str = N;
pub var staticName: Name = .{ .string = str, .index = null };
pub fn ToName() Name {
.{ .string = N, .index = null };
}
pub fn get() Name {
return staticName;
}
pub fn handle() u32 {
return staticName.handle();
}
pub fn utf() []const u8 {
return staticName.utf8();
}
};
}
test "zname initialization and lookup" {
_ = try createNameRegistry(std.testing.allocator, std.testing.io);
defer destroyNameRegistry();
const testComptimeName = "This is a name test";
const testComptimeName2 = "This is another name test";
var r = getRegistry();
var name = MakeName(testComptimeName);
var name2 = r.name(testComptimeName);
var name4 = r.name(testComptimeName2);
const fmtString = try std.fmt.allocPrint(std.testing.allocator, "morty I did horrible things to your {s}.", .{"locally elected representative"});
defer std.testing.allocator.free(fmtString);
var name3 = r.name(fmtString);
try std.testing.expectEqualSlices(u8, testComptimeName, name.utf8());
try std.testing.expectEqualSlices(u8, testComptimeName, name2.utf8());
try std.testing.expect(name2.eql(&name));
try std.testing.expect(!name3.eql(&name));
var uninitializedName: Name = .{};
var invalidName = r.name("Invalid");
try std.testing.expect(uninitializedName.eql(&invalidName));
try std.testing.expect(!name4.eql(&name3));
try std.testing.expectEqualSlices(u8, name3.utf8(), fmtString);
}

View File

@ -0,0 +1,323 @@
const std = @import("std");
const stats = @import("stats.zig");
// it's like an normal vector/ arraylist except it never invalidates old pointers.
// and never causes re-allocations. (excepting in the control block, which is just a vector of things)
//
// It is implemented with a control block which which contains a list of pages.
// these pages contain the actual memory of the vector.
//
// it has a growth factor, which can be configured.
//
// use cases:
//
// - this is highly performant for cases where
// - YOU WANT generally fast insertion time
// - YOU WANT fast random access time
// - YOU WANT cache-coherent and efficient linear iteration
// - YOU WANT to retain pointers across operations
// - YOU WANT to avoid reallocations (eg. if the data set is remarkably big)
// - YOU KNOW that you have linear growth factors and exponential growth is overkill.
//
// great for:
// - event logging.
// - output buffering.
// - recording timelines.
pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type {
return struct {
const Page = struct {
data: [growth]T align(8) = undefined,
len: u32 = 0,
};
pages: std.ArrayListUnmanaged(*Page) = .empty,
currentPageId: usize = 0,
head: *T,
pub fn init(allocator: std.mem.Allocator) !@This() {
var rv = @This(){
.head = undefined,
};
const page = try allocator.create(Page);
page.* = .{};
try rv.pages.append(allocator, page);
rv.head = &rv.pages.items[0].data[0];
return rv;
}
pub fn capacity(self: @This()) usize {
return self.pages.items.len * growth;
}
pub fn len(self: @This()) usize {
return (self.currentPageId) * growth + self.currentPage().len;
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return .{
.statName = "PagedVector",
.instanceCount = self.len(),
.memoryReserved = self.pages.items.len * @sizeOf(Page) +
self.pages.capacity * @sizeOf(*Page),
.memoryUsed = self.len() * @sizeOf(T),
};
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
for (self.pages.items) |page| {
allocator.destroy(page);
}
self.pages.deinit(allocator);
}
fn maybeExpand(self: *@This(), allocator: std.mem.Allocator) !void {
if (self.currentPageId == self.pages.items.len - 1) {
const page = try allocator.create(Page);
page.* = .{};
try self.pages.append(allocator, page);
self.currentPageId = self.pages.items.len - 1;
} else {
self.currentPageId += 1;
}
}
// frees all pages. and resets back to default state
pub fn reset(self: *@This(), allocator: std.mem.Allocator) void {
if (self.pages.items.len > 1) {
for (self.pages.items[1..]) |page| {
allocator.destroy(page);
}
self.pages.items.len = 1;
}
self.pages.items[0].len = 0;
self.currentPageId = 0;
self.head = &self.pages.items[0].data[0];
}
pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void {
var page = self.currentPage();
page.len += 1;
if (page.len >= growth) {
try self.maybeExpand(allocator);
var appendedPage = self.pages.items[self.pages.items.len - 1];
self.head = &appendedPage.data[appendedPage.len];
} else {
self.head = &page.data[page.len - 1];
}
self.head.* = value;
}
pub fn appendSlice(self: *@This(), allocator: std.mem.Allocator, slice: []const T) !void {
for (slice) |value| {
try self.append(allocator, value);
}
}
pub fn getMutable(self: *@This(), index: usize) *T {
const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable;
return &self.pages.items[pageIndex].data[index % growth];
}
pub fn get(self: @This(), index: usize) *const T {
const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable;
return &self.pages.items[pageIndex].data[index % growth];
}
// swaps the element at the index with the element currently pointed to by head
// then pops back the head, shrinking length by 1
//
// Efficient removal of an element at an index but does not preserve order.
pub fn swapRemove(self: *@This(), index: usize) void {
const ptr = self.getMutable(index);
ptr.* = self.head.*;
_ = try self.pop();
}
fn currentPage(self: @This()) *Page {
return self.pages.items[self.currentPageId];
}
// // retrieves a value, shrinking length by 1
pub fn pop(self: *@This()) !T {
const rv = self.head.*;
var page = self.currentPage();
page.len -= 1;
if (page.len < 1) {
page.len = 0;
self.currentPageId -= 1;
}
self.head = &self.currentPage().data[self.currentPage().len - 1];
return rv;
}
};
}
pub fn PagedVectorUnmanaged(comptime T: type) type {
return PagedVectorAdvanced(T, 1024);
}
pub fn PagedVector(comptime T: type) type {
return struct {
const VectorType = PagedVectorAdvanced(T, 1024);
vector: VectorType,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) !@This() {
return .{
.vector = try VectorType.init(allocator),
.allocator = allocator,
};
}
pub fn deinit(self: *@This()) void {
self.vector.deinit(self.allocator);
}
pub fn appendSlice(self: *@This(), slice: []const T) !void {
try self.vector.appendSlice(self.allocator, slice);
}
pub fn append(self: *@This(), value: T) !void {
try self.vector.append(self.allocator, value);
}
pub fn appendAndGet(self: *@This(), value: T) !*T {
const index = self.len();
try self.append(value);
return self.getMutable(index);
}
pub fn get(self: *const @This(), index: usize) *const T {
return self.vector.get(index);
}
pub fn getMutable(self: *@This(), index: usize) *T {
return self.vector.getMutable(index);
}
pub fn len(self: @This()) usize {
return self.vector.len();
}
pub fn capacity(self: @This()) usize {
return self.vector.capacity();
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return self.vector.getStatistics();
}
pub fn swapRemove(self: *@This(), index: usize) void {
self.vector.swapRemove(index);
}
pub fn reset(self: *@This()) void {
self.vector.reset(self.allocator);
}
// // retrieves a value, shrinking length by 1
pub fn pop(self: *@This()) !T {
return try self.vector.pop();
}
};
}
test "simple loading multiple pages." {
const TestStruct = struct {
lmao: usize,
};
const allocator = std.testing.allocator;
var vector = try PagedVectorAdvanced(TestStruct, 1024).init(std.testing.allocator);
defer vector.deinit(allocator);
for (0..128) |j| {
try vector.append(allocator, .{ .lmao = j });
}
const ptr = vector.get(0);
const mutable = vector.getMutable(127);
for (0..4096) |i| {
try vector.append(allocator, .{ .lmao = i });
}
// testing that pointers are not invalidated
std.debug.assert(ptr == vector.get(0));
std.debug.assert(mutable == vector.getMutable(127));
std.debug.assert(vector.getMutable(4092) == vector.getMutable(4092));
// 4096 + 128 = 4224 = 4 pages + 128 extra entries
std.debug.assert(vector.pages.items.len == 5);
std.debug.assert(vector.capacity() == 1024 * 5);
std.debug.assert(vector.len() == 128 + 1024 * 4);
// 4092 - 3072 = offset of 1020 in the third page.
const ptr4092 = vector.getMutable(4092);
std.debug.assert(vector.getMutable(4092) == &vector.pages.items[3].data[1020]);
// lets try adding 1024 elements and see if pointers are still preserved.
for (0..1024) |_| {
try vector.append(allocator, .{ .lmao = 0 });
}
std.debug.assert(vector.getMutable(4092) == ptr4092);
std.debug.assert(vector.get(0).lmao == 0);
std.debug.assert(vector.get(1).lmao == 1);
std.debug.assert(vector.get(2).lmao == 2);
// testing the pop() function
std.debug.assert(vector.len() == 128 + 1024 * 5);
_ = try vector.pop();
_ = try vector.pop();
_ = try vector.pop();
// testing the swapRemove Functionality
std.debug.assert(vector.len() == 128 + 1024 * 5 - 3);
vector.swapRemove(1);
std.debug.assert(vector.len() == 128 + 1024 * 5 - 4);
for (0..1024) |_| {
vector.swapRemove(0);
}
std.debug.assert(vector.len() == 128 + 1024 * 5 - 4 - 1024);
}
test "managed version" {
const allocator = std.testing.allocator;
var vec = try PagedVector(struct { lmao: u64 }).init(allocator);
defer vec.deinit();
for (0..8192) |i| {
try vec.append(.{ .lmao = i });
}
std.debug.assert(vec.vector.pages.items.len == 9);
}
test "reset releases extra pages and clears length" {
const allocator = std.testing.allocator;
var vec = try PagedVectorAdvanced(u32, 4).init(allocator);
defer vec.deinit(allocator);
for (0..10) |i| {
try vec.append(allocator, @intCast(i));
}
try std.testing.expect(vec.pages.items.len > 1);
vec.reset(allocator);
try std.testing.expectEqual(@as(usize, 1), vec.pages.items.len);
try std.testing.expectEqual(@as(usize, 0), vec.len());
try vec.append(allocator, 42);
try std.testing.expectEqual(@as(u32, 42), vec.get(0).*);
}

View File

@ -0,0 +1,190 @@
const std = @import("std");
const sparse_set = @import("sparse-set.zig");
fn println(comptime fmt: []const u8, args: anytype) void {
std.debug.print(fmt ++ "\n", args);
}
const LookupPerfContext = struct {
testName: []const u8 = "lookup perf 1 Billion Accesses",
dsName: std.ArrayList([]const u8), // name of data structures
testSizes: std.ArrayList(usize),
testTimes: std.ArrayList(std.ArrayList(f64)), //
pub fn init(allocator: std.mem.Allocator) @This() {
_ = allocator;
return .{
.dsName = .empty,
.testSizes = .empty,
.testTimes = .empty,
};
}
pub fn printResults(self: @This()) void {
// prints out results in a csv format
println("Test Results: {s}", .{self.testName});
std.debug.print("number of elements,", .{});
for (self.dsName.items) |name| {
std.debug.print("{s},", .{name});
}
std.debug.print("\n", .{});
std.debug.assert(self.testSizes.items.len == self.testTimes.items.len);
var i: usize = 0;
while (i < self.testSizes.items.len) : (i += 1) {
std.debug.print("{d},", .{self.testSizes.items[i]});
const times = self.testTimes.items[i];
for (times.items) |entry| {
std.debug.print("{d},", .{entry});
}
std.debug.print("\n", .{});
}
}
};
fn nowNs(io: std.Io) i96 {
return std.Io.Timestamp.now(io, .awake).toNanoseconds();
}
fn elapsedSeconds(start_ns: i96, end_ns: i96) f64 {
return @as(f64, @floatFromInt(end_ns - start_ns)) / @as(f64, @floatFromInt(std.time.ns_per_s));
}
pub fn LookupPerfTest(io: std.Io, allocator: std.mem.Allocator, perfContext: *LookupPerfContext, comptime TestSize: comptime_int, comptime AccessCount: comptime_int) !void {
var testTimes: std.ArrayList(f64) = .empty;
try testTimes.appendSlice(allocator, &.{
0.0,
0.0,
0.0,
0.0,
});
const TestPayload = struct {
touchCount: u32 = 0,
name: []const u8 = "payload",
};
// Doing a test of 1 million accesses to random sparse set handles to one thousand hashmap lookups
const TestMap = std.AutoHashMap(u32, TestPayload);
const TestSet = sparse_set.SparseMultiSet(struct {
obj: TestPayload = .{},
});
println(" === preparing test with {d} entries === ", .{TestSize});
var testMap = TestMap.init(allocator);
defer testMap.deinit();
var i: usize = 0;
while (i < TestSize) : (i += 1) {
try testMap.put(@as(u32, @intCast(i)), .{});
}
i = 0;
var hashMapTime: f64 = 0;
{
const startTime = nowNs(io);
// random access for 1M.
while (i < AccessCount) : (i += 1) {
const id = @as(u32, @intCast(i % TestSize));
testMap.getEntry(id).?.value_ptr.*.touchCount += 1;
}
const endTime = nowNs(io);
println("hashMap: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) });
hashMapTime = elapsedSeconds(startTime, endTime); // index 0
testTimes.items[0] = hashMapTime;
}
var hashmap_linear_time: f64 = 0;
{
i = 0;
const startTime = nowNs(io);
// random access for 1M.
while (i < AccessCount) : (i += 1) {
var iter = testMap.iterator();
while (iter.next()) |entry| {
entry.value_ptr.*.touchCount += 1;
i += 1;
}
}
const endTime = nowNs(io);
println("hashMap_linear: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) });
hashmap_linear_time = elapsedSeconds(startTime, endTime);
testTimes.items[2] = hashmap_linear_time;
}
// --- testing sparse sets
var testSet = TestSet.init(allocator);
defer testSet.deinit();
var handlesList: std.ArrayList(sparse_set.SetHandle) = .empty;
i = 0;
while (i < TestSize) : (i += 1) {
const newHandle = try testSet.createObject(.{});
try handlesList.append(allocator, newHandle);
}
var sparseSetTime: f64 = 0;
i = 0;
{
const startTime = nowNs(io);
while (i < AccessCount) : (i += 1) {
testSet.get(handlesList.items[i % TestSize], .obj).?.*.touchCount += 1;
}
const endTime = nowNs(io);
println("sparseSet: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) });
sparseSetTime = elapsedSeconds(startTime, endTime);
testTimes.items[1] = sparseSetTime;
}
// linear access
var sparseset_linear_time: f64 = 0;
i = 0;
{
const startTime = nowNs(io);
var denseArray = testSet.denseItems(.obj);
while (i < AccessCount) : (i += 1) {
denseArray[i % TestSize].touchCount += 1;
}
const endTime = nowNs(io);
sparseset_linear_time = elapsedSeconds(startTime, endTime);
println("sparseSet_linear: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) });
testTimes.items[3] = sparseset_linear_time;
}
println("random read: sparseSet is {d} times faster than hashmap", .{hashMapTime / sparseSetTime});
println("sequential read: sparseSet is {d} times faster than hashmap", .{hashmap_linear_time / sparseset_linear_time});
try perfContext.testTimes.append(allocator, testTimes);
try perfContext.testSizes.append(allocator, TestSize);
}
const K = 1000;
const M = 1000 * K;
const G = 1000 * M;
pub fn count(comptime n: anytype) [n]u0 {
return comptime [1]u0{0} ** n;
}
test "Perf test sparse vs hashmap" {
// this test does NOT care about freeing memory, just gonna let the arena hit it.
var arena = std.heap.ArenaAllocator.init(std.heap.smp_allocator);
defer arena.deinit();
const arenaAlloc = arena.allocator();
var context = LookupPerfContext.init(arenaAlloc);
try context.dsName.append(arenaAlloc, "hashmap random");
try context.dsName.append(arenaAlloc, "sparseSet random");
try context.dsName.append(arenaAlloc, "hashmap linear");
try context.dsName.append(arenaAlloc, "sparseset linear");
inline for (comptime count(100 - 1), 0..) |_, i| {
try LookupPerfTest(std.testing.io, arenaAlloc, &context, (i + 1) * (100 * K) / 100, 100 * M);
}
context.printResults();
}

View File

@ -0,0 +1,165 @@
// pscopes
//
// a tiny scope based profiling library
// as well as contains info for arbitrary timestamping and timestamp resolution
const timestampTicks = if (builtin.target.cpu.arch == .x86_64) rdtsc else aarch64_ticks;
// rdtsc actually gets read
pub inline fn rdtsc() u64 {
var hi: u32 = 0;
var lo: u32 = 0;
asm (
\\rdtsc
: [lo] "={eax}" (lo),
[hi] "={edx}" (hi),
);
return (@as(u64, hi) << 32) | @as(u64, lo);
}
fn aarch64_ticks() u64 {
return asm volatile ("mrs %[ret], CNTVCT_EL0"
: [ret] "=r" (-> u64),
);
}
fn aarch64_freq() u64 {
return asm volatile ("mrs %[ret], CNTFRQ_EL0"
: [ret] "=r" (-> u64),
);
}
fn countTo1Million() u32 {
var i: u32 = 0;
while (i < 1000 * 1000) : (i += 1) {}
return i;
}
fn countTo1Billion() u32 {
var i: u32 = 0;
while (i < 1000 * 1000 * 1000) : (i += 1) {}
return i;
}
pub const TimingScope = struct {
// value in tsc ticks
startTsc: u64,
endTsc: ?u64 = null,
context: *ScopesContext,
pub inline fn init(c: *ScopesContext) @This() {
return .{
.startTsc = timestampTicks(),
.context = c,
};
}
pub fn duration(self: *@This()) ?f64 {
if (self.endTsc) |endTsc| {
if (self.context.ticksPerMs) |ticksPerMs| {
const x = @as(f64, @floatFromInt(endTsc - self.startTsc)) / ticksPerMs / 1000;
return x;
}
}
return null;
}
pub inline fn end(self: *@This()) void {
self.endTsc = timestampTicks();
}
};
pub const ScopesContext = struct {
allocator: std.mem.Allocator,
io_context: std.Io,
ticksPerMs: ?f64 = null,
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
// creates a very simple scope, the only thing it does is store the timestamp, and move on
pub fn stampScope(self: *@This()) TimingScope {
return .{
.startTsc = timestampTicks(),
.endTsc = null,
.context = self,
};
}
// calibrates the ticks per second divider.
// spins for 1 ms then compares against the monotonic timer
// should be called once every second, this is kinda perscriptive,
// calling it more frequently will increase accuracy
pub fn calibrate(self: *@This()) void {
if (builtin.target.cpu.arch == .x86_64) {
const startTime = std.Io.Timestamp.now(self.io(), .awake);
const startStamp = rdtsc();
while (startTime.durationTo(std.Io.Timestamp.now(self.io(), .awake)).toNanoseconds() < std.time.ns_per_ms) {}
const endStamp = rdtsc();
self.ticksPerMs = @floatFromInt((endStamp - startStamp));
} else if (builtin.target.cpu.arch == .aarch64) {
self.ticksPerMs = @as(f64, @floatFromInt(aarch64_freq())) / 1000;
} else {
// not ticking
// unreachable;
}
}
pub fn create(allocator: std.mem.Allocator, io_context: std.Io) !*@This() {
const self = try allocator.create(@This());
self.* = .{
.allocator = allocator,
.io_context = io_context,
};
return self;
}
pub fn destroy(self: *@This()) void {
self.allocator.destroy(self);
}
};
test "calibrate scoes" {
const allocator = std.testing.allocator;
const scopes = try ScopesContext.create(allocator, std.testing.io);
defer scopes.destroy();
scopes.calibrate();
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
scopes.calibrate();
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
scopes.calibrate();
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
{
var scope = scopes.stampScope();
_ = countTo1Billion();
scope.end();
std.debug.print("time elapsed: {d}\n ", .{scope.duration().?});
}
{
var z = scopes.stampScope();
defer z.end();
_ = countTo1Million();
}
{
var z = scopes.stampScope();
defer z.end();
_ = countTo1Million();
}
}
const std = @import("std");
const builtin = @import("builtin");
const pscopes_zig_src = @embedFile("pscopes.zig");

View File

@ -0,0 +1,658 @@
const std = @import("std");
const stats = @import("stats.zig");
const index_pool = @import("index-pool.zig");
pub const RefPoolOptions = struct {
deferredDestruction: bool = false,
};
/// A dense value pool with strong, reference-counted handles.
///
/// This default form destroys values immediately after their final `drop`.
/// Use `RefPoolAdvanced` to opt into deferred destruction.
pub fn RefPool(comptime T: type) type {
return RefPoolAdvanced(T, .{});
}
// Deffered destruction version of refpool
// owning system MUST tick the trim() function,
// provides lifetime destruction hooks for each entry.
pub fn RefPoolDeferred(comptime T: type) type {
return RefPoolAdvanced(T, .{});
}
/// A dense value pool with strong, reference-counted handles.
///
/// RefPool is backed by an IndexPool and shares its storage model and handle
/// layout, but handles own the value they address: `new` creates a value with
/// one reference, `pin` adds a reference, and `drop` releases one.
///
/// A final `drop` makes the handle logically dead immediately. With immediate
/// destruction it also removes the value at once. With deferred destruction
/// it queues the value for a later `trim`; the zero-pin entry remains in the
/// backing pool and its slot cannot be reused until then.
///
/// Handles are generational like IndexPool handles. Copying a handle without
/// calling `pin` is a contract violation. An optional `onDestroy` callback can
/// release resources owned by `T`; without one, removed values are discarded.
/// The callback receives a temporary pointer that is valid only for that call.
///
/// The backing `pool` remains exposed for dense iteration and low-level slot
/// bookkeeping. In deferred mode its dense storage includes queued zero-pin
/// entries; callers must not treat those entries as live. Do not call `new` or
/// `destroy` on the backing pool directly.
///
/// Pointers and slices returned by this type are invalidated by `new`, an
/// immediate destroying `drop`, `trim`, `releaseAllFreeSlots`, or `deinit`.
/// A final deferred `drop` logically invalidates pointers to that value even
/// though physical removal waits for `trim`.
///
/// Releasing every reference during normal operation is the caller's
/// responsibility. `deinit` defensively destroys pending and still-pinned
/// entries. Handles belong to one pool instance. `releaseAllFreeSlots` is a
/// full epoch boundary: callers must discard every handle, including stale
/// handles, before calling it because released generation history is lost.
///
/// This type is not thread-safe.
pub fn RefPoolAdvanced(comptime T: type, comptime options: RefPoolOptions) type {
return struct {
const Self = @This();
pub const PinCount = u32;
/// Dense storage element. The pin count travels with the value under
/// IndexPool's swap-remove; handle stability comes from the slot
/// table underneath. A zero pin count marks deferred destruction.
pub const Entry = struct {
value: T,
pins: PinCount,
};
pub const Pool = index_pool.IndexPool(Entry);
pub const Handle = index_pool.TypedHandle(T);
pub const OnDestroyFn = *const fn (context: ?*anyopaque, value: *T) void;
const InnerHandle = Pool.Handle;
const OnDestroyBinding = struct {
context: ?*anyopaque,
callback: OnDestroyFn,
};
const PendingDestroyList = if (options.deferredDestruction)
std.ArrayList(Handle)
else
struct {
const empty: @This() = .{};
};
pub const maxSlotCount: usize = Pool.maxSlotCount;
pub const CapacityError = Pool.CapacityError;
allocator: std.mem.Allocator,
/// The backing pool. Direct mutation bypasses RefPool's ownership
/// invariants and is unsupported.
pool: Pool,
pendingDestroy: PendingDestroyList = .empty,
onDestroy: ?OnDestroyBinding = null,
callbackDepth: usize = 0,
trimming: bool = false,
deinitializing: bool = false,
pub fn init(allocator: std.mem.Allocator) Self {
return .{
.allocator = allocator,
.pool = Pool.init(allocator),
};
}
/// Initializes a pool with capacity for `capacity` live, free, or
/// pending slots. A final `drop` and `trim` remain allocation-free.
pub fn initCapacity(allocator: std.mem.Allocator, capacity: usize) CapacityError!Self {
var self = init(allocator);
errdefer self.deinit();
try self.ensureTotalCapacity(capacity);
return self;
}
/// Reserves dense, slot, free-list, and deferred-destruction storage.
pub fn ensureTotalCapacity(self: *Self, capacity: usize) CapacityError!void {
if (capacity > maxSlotCount) return error.PoolFull;
if (comptime options.deferredDestruction) {
try self.pendingDestroy.ensureTotalCapacity(self.allocator, capacity);
}
try self.pool.ensureTotalCapacity(capacity);
}
fn toInner(handle: Handle) InnerHandle {
return @bitCast(handle);
}
/// Number of logically live values. Deferred zero-pin entries are not
/// included even though they remain in backing storage until `trim`.
pub fn count(self: *const Self) usize {
return self.pool.count() - self.pendingDestroyCount();
}
/// Number of values awaiting physical removal and `onDestroy`.
pub fn pendingDestroyCount(self: *const Self) usize {
if (comptime options.deferredDestruction) {
return self.pendingDestroy.items.len;
}
return 0;
}
/// Number of allocated handle slots, including free, pending, and
/// retired slots.
pub fn slotCount(self: *const Self) usize {
return self.pool.slotCount();
}
/// Number of slots available for immediate allocation-free reuse.
/// Deferred entries do not become free until `trim` removes them.
pub fn freeCount(self: *const Self) usize {
return self.pool.freeCount();
}
pub fn getStatistics(self: *const Self) stats.PoolStatistics {
var poolStats = self.pool.getStatistics();
poolStats.statName = "RefPool";
poolStats.instanceCount = self.count();
if (comptime options.deferredDestruction) {
poolStats.memoryReserved += self.pendingDestroy.capacity * @sizeOf(Handle);
poolStats.memoryUsed += self.pendingDestroy.items.len * @sizeOf(Handle);
}
return poolStats;
}
/// Installs or replaces the pool-wide destruction callback. The
/// context and function must remain valid through every later destroy
/// operation, including `deinit`, unless explicitly unregistered.
pub fn registerOnDestroy(self: *Self, context: ?*anyopaque, callback: OnDestroyFn) void {
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.trimming);
std.debug.assert(!self.deinitializing);
self.onDestroy = .{
.context = context,
.callback = callback,
};
}
/// Clears the callback. Values destroyed afterward are discarded.
pub fn unregisterOnDestroy(self: *Self) void {
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.trimming);
std.debug.assert(!self.deinitializing);
self.onDestroy = null;
}
/// Creates a value with one reference and returns its owning handle.
pub fn new(self: *Self, initVal: T) CapacityError!Handle {
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.deinitializing);
// A free slot already has matching dense and pending capacity.
// Growing the slot table must reserve every backing structure
// before IndexPool's allocation-free append path is entered.
if (self.pool.freeCount() == 0) {
if (self.pool.slotCount() == maxSlotCount) return error.PoolFull;
try self.ensureTotalCapacity(self.pool.slotCount() + 1);
}
const inner = try self.pool.new(.{
.value = initVal,
.pins = 1,
});
return @bitCast(inner);
}
pub fn isValid(self: *const Self, handle: Handle) bool {
const entry = self.pool.getRead(toInner(handle)) orelse return false;
return entry.pins != 0;
}
/// Adds a reference to a live value. Pending, invalid, and stale
/// handles return false without changing the pool.
pub fn pin(self: *Self, handle: Handle) bool {
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.deinitializing);
const entry = self.pool.get(toInner(handle)) orelse return false;
if (entry.pins == 0) return false;
std.debug.assert(entry.pins < std.math.maxInt(PinCount));
entry.pins += 1;
return true;
}
/// Releases one reference. Returns false for invalid, stale, already
/// pending, and duplicate handles. A final drop either destroys the
/// value immediately or queues it for `trim`, depending on the
/// compile-time configuration. This operation never allocates.
pub fn drop(self: *Self, handle: Handle) bool {
const inner = toInner(handle);
const entry = self.pool.get(inner) orelse return false;
if (entry.pins == 0) return false;
entry.pins -= 1;
if (entry.pins != 0) return true;
if (comptime options.deferredDestruction) {
std.debug.assert(self.pendingDestroy.items.len < self.pendingDestroy.capacity);
self.pendingDestroy.appendAssumeCapacity(handle);
} else {
var removed = self.pool.destroy(inner).?;
self.invokeOnDestroy(&removed.value);
}
return true;
}
/// Current reference count of a live value, null for pending,
/// invalid, or stale handles.
pub fn pinCount(self: *const Self, handle: Handle) ?PinCount {
const entry = self.pool.getRead(toInner(handle)) orelse return null;
if (entry.pins == 0) return null;
return entry.pins;
}
pub fn get(self: *Self, handle: Handle) ?*T {
const entry = self.pool.get(toInner(handle)) orelse return null;
if (entry.pins == 0) return null;
return &entry.value;
}
pub fn getRead(self: *const Self, handle: Handle) ?*const T {
const entry = self.pool.getRead(toInner(handle)) orelse return null;
if (entry.pins == 0) return null;
return &entry.value;
}
/// Physically removes every pending value and invokes the currently
/// registered callback. Drops performed by callbacks are included in
/// the same drain. Returns the number of values removed.
pub fn trim(self: *Self) usize {
if (comptime !options.deferredDestruction) return 0;
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.trimming);
std.debug.assert(!self.deinitializing);
self.trimming = true;
defer self.trimming = false;
return self.drainPending();
}
/// Fully releases pool storage when there are no live or pending
/// values. This is a full epoch boundary; every associated handle must
/// be discarded first.
pub fn releaseAllFreeSlots(self: *Self) bool {
if (self.pool.count() != 0 or self.pendingDestroyCount() != 0) return false;
const releasedPoolStorage = self.pool.releaseAllFreeSlots();
if (comptime options.deferredDestruction) {
const releasedPendingStorage = self.pendingDestroy.capacity != 0;
if (releasedPendingStorage) {
self.pendingDestroy.clearAndFree(self.allocator);
}
return releasedPoolStorage or releasedPendingStorage;
}
return releasedPoolStorage;
}
/// Destroys pending and still-pinned entries, then releases storage.
pub fn deinit(self: *Self) void {
std.debug.assert(self.callbackDepth == 0);
std.debug.assert(!self.trimming);
std.debug.assert(!self.deinitializing);
self.deinitializing = true;
_ = self.drainPending();
while (self.pool.count() != 0) {
// A callback may have dropped other values. Drain those first
// so their queued handles never become stale inside the list.
if (self.pendingDestroyCount() != 0) {
_ = self.drainPending();
continue;
}
const denseIndex = self.pool.count() - 1;
const handle = self.pool.handleAtDenseIndex(denseIndex).?;
var removed = self.pool.destroy(handle).?;
self.invokeOnDestroy(&removed.value);
}
if (comptime options.deferredDestruction) {
std.debug.assert(self.pendingDestroy.items.len == 0);
self.pendingDestroy.deinit(self.allocator);
}
self.pool.deinit();
self.* = undefined;
}
fn drainPending(self: *Self) usize {
if (comptime !options.deferredDestruction) return 0;
var destroyed: usize = 0;
while (self.pendingDestroy.pop()) |handle| {
const inner = toInner(handle);
const entry = self.pool.get(inner) orelse continue;
std.debug.assert(entry.pins == 0);
var removed = self.pool.destroy(inner).?;
self.invokeOnDestroy(&removed.value);
destroyed += 1;
}
return destroyed;
}
fn invokeOnDestroy(self: *Self, value: *T) void {
const binding = self.onDestroy orelse return;
std.debug.assert(self.callbackDepth < std.math.maxInt(usize));
self.callbackDepth += 1;
defer self.callbackDepth -= 1;
binding.callback(binding.context, value);
}
};
}
const TestValue = struct {
id: u32,
};
const TestPool = RefPool(TestValue);
const DeferredTestPool = RefPoolAdvanced(TestValue, .{ .deferredDestruction = true });
const DestroyContext = struct {
ids: [16]u32 = undefined,
count: usize = 0,
fn onDestroy(rawContext: ?*anyopaque, value: *TestValue) void {
const self: *@This() = @ptrCast(@alignCast(rawContext.?));
self.ids[self.count] = value.id;
self.count += 1;
}
};
test "ref pool handles are typed and zero-invalid" {
try std.testing.expect(RefPool(u32).Handle != RefPool(u64).Handle);
try std.testing.expectEqual(@as(usize, 4), @sizeOf(TestPool.Handle));
try std.testing.expectEqual(@as(usize, 1) << 18, TestPool.maxSlotCount);
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
try std.testing.expect(!pool.isValid(.{}));
try std.testing.expect(!pool.pin(.{}));
try std.testing.expect(!pool.drop(.{}));
const handle = try pool.new(.{ .id = 42 });
try std.testing.expect(handle.generation != 0);
try std.testing.expect(pool.isValid(handle));
try std.testing.expectEqual(@as(u32, 42), pool.get(handle).?.id);
try std.testing.expectEqual(@as(TestPool.PinCount, 1), pool.pinCount(handle).?);
}
test "ref pool invokes onDestroy on an immediate final drop" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
var context: DestroyContext = .{};
pool.registerOnDestroy(&context, DestroyContext.onDestroy);
const handle = try pool.new(.{ .id = 1 });
try std.testing.expect(pool.pin(handle));
try std.testing.expect(pool.pin(handle));
try std.testing.expectEqual(@as(TestPool.PinCount, 3), pool.pinCount(handle).?);
try std.testing.expect(pool.drop(handle));
try std.testing.expect(pool.isValid(handle));
try std.testing.expect(pool.drop(handle));
try std.testing.expectEqual(@as(TestPool.PinCount, 1), pool.pinCount(handle).?);
try std.testing.expectEqual(@as(usize, 0), context.count);
try std.testing.expect(pool.drop(handle));
try std.testing.expectEqual(@as(usize, 1), context.count);
try std.testing.expectEqual(@as(u32, 1), context.ids[0]);
try std.testing.expect(!pool.isValid(handle));
try std.testing.expect(pool.pinCount(handle) == null);
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.trim());
}
test "ref pool unregisters onDestroy and rejects stale drops" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
var context: DestroyContext = .{};
pool.registerOnDestroy(&context, DestroyContext.onDestroy);
pool.unregisterOnDestroy();
const original = try pool.new(.{ .id = 1 });
try std.testing.expect(pool.drop(original));
try std.testing.expectEqual(@as(usize, 0), context.count);
try std.testing.expect(!pool.isValid(original));
try std.testing.expect(!pool.pin(original));
try std.testing.expect(!pool.drop(original));
try std.testing.expect(pool.get(original) == null);
const replacement = try pool.new(.{ .id = 2 });
try std.testing.expectEqual(original.index, replacement.index);
try std.testing.expect(original.generation != replacement.generation);
try std.testing.expect(!pool.drop(original));
try std.testing.expectEqual(@as(u32, 2), pool.get(replacement).?.id);
}
test "ref pool keeps immediate survivors dense" {
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
const first = try pool.new(.{ .id = 1 });
const middle = try pool.new(.{ .id = 2 });
const last = try pool.new(.{ .id = 3 });
try std.testing.expect(pool.pin(last));
try std.testing.expect(pool.drop(middle));
try std.testing.expectEqual(@as(usize, 2), pool.count());
try std.testing.expectEqual(@as(u32, 1), pool.get(first).?.id);
try std.testing.expectEqual(@as(u32, 3), pool.get(last).?.id);
try std.testing.expectEqual(@as(TestPool.PinCount, 2), pool.pinCount(last).?);
const entries = pool.pool.items();
try std.testing.expectEqual(@as(usize, 2), entries.len);
try std.testing.expectEqual(@as(u32, 1), entries[0].value.id);
try std.testing.expectEqual(@as(u32, 3), entries[1].value.id);
try std.testing.expectEqual(@as(TestPool.PinCount, 2), entries[1].pins);
}
test "deferred final drop invalidates logically until trim" {
var pool = try DeferredTestPool.initCapacity(std.testing.allocator, 2);
defer pool.deinit();
var context: DestroyContext = .{};
pool.registerOnDestroy(&context, DestroyContext.onDestroy);
const original = try pool.new(.{ .id = 1 });
try std.testing.expect(pool.drop(original));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 1), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 1), pool.pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
try std.testing.expectEqual(@as(usize, 0), context.count);
try std.testing.expect(!pool.isValid(original));
try std.testing.expect(!pool.pin(original));
try std.testing.expect(!pool.drop(original));
try std.testing.expect(pool.get(original) == null);
try std.testing.expect(pool.getRead(original) == null);
try std.testing.expect(pool.pinCount(original) == null);
try std.testing.expect(!pool.releaseAllFreeSlots());
const other = try pool.new(.{ .id = 2 });
try std.testing.expect(original.index != other.index);
try std.testing.expectEqual(@as(usize, 1), pool.count());
try std.testing.expectEqual(@as(usize, 2), pool.pool.items().len);
try std.testing.expectEqual(@as(usize, 1), pool.trim());
try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 1), pool.count());
try std.testing.expectEqual(@as(usize, 1), pool.freeCount());
try std.testing.expectEqual(@as(usize, 1), context.count);
try std.testing.expectEqual(@as(u32, 1), context.ids[0]);
const replacement = try pool.new(.{ .id = 3 });
try std.testing.expectEqual(original.index, replacement.index);
try std.testing.expect(original.generation != replacement.generation);
}
const CascadeValue = struct {
id: u32,
childBits: ?u32 = null,
};
const CascadePool = RefPoolAdvanced(CascadeValue, .{ .deferredDestruction = true });
const CascadeContext = struct {
pool: *CascadePool,
ids: [4]u32 = undefined,
count: usize = 0,
fn onDestroy(rawContext: ?*anyopaque, value: *CascadeValue) void {
const self: *@This() = @ptrCast(@alignCast(rawContext.?));
self.ids[self.count] = value.id;
self.count += 1;
if (value.childBits) |bits| {
const child: CascadePool.Handle = @bitCast(bits);
std.debug.assert(self.pool.drop(child));
}
}
};
test "deferred trim drains callback-triggered drops" {
var pool = try CascadePool.initCapacity(std.testing.allocator, 2);
defer pool.deinit();
var context: CascadeContext = .{ .pool = &pool };
pool.registerOnDestroy(&context, CascadeContext.onDestroy);
const child = try pool.new(.{ .id = 1 });
const parent = try pool.new(.{
.id = 2,
.childBits = @bitCast(child),
});
try std.testing.expect(pool.drop(parent));
try std.testing.expectEqual(@as(usize, 1), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 2), pool.trim());
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 2), context.count);
try std.testing.expectEqual(@as(u32, 2), context.ids[0]);
try std.testing.expectEqual(@as(u32, 1), context.ids[1]);
}
test "ref pool deinit destroys pending and still-pinned values" {
var pool = try DeferredTestPool.initCapacity(std.testing.allocator, 2);
var context: DestroyContext = .{};
pool.registerOnDestroy(&context, DestroyContext.onDestroy);
const pending = try pool.new(.{ .id = 1 });
const pinned = try pool.new(.{ .id = 2 });
try std.testing.expect(pool.pin(pinned));
try std.testing.expect(pool.drop(pending));
pool.deinit();
try std.testing.expectEqual(@as(usize, 2), context.count);
try std.testing.expectEqual(@as(u32, 1), context.ids[0]);
try std.testing.expectEqual(@as(u32, 2), context.ids[1]);
}
test "ref pool reserves storage so immediate pin and drop never allocate" {
var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var pool = try TestPool.initCapacity(allocatorState.allocator(), 8);
defer pool.deinit();
const allocationsAfterReserve = allocatorState.allocations;
var handles: [8]TestPool.Handle = undefined;
for (&handles, 0..) |*handle, i| {
handle.* = try pool.new(.{ .id = @intCast(i) });
try std.testing.expect(pool.pin(handle.*));
}
try std.testing.expect(!pool.releaseAllFreeSlots());
for (handles) |handle| {
try std.testing.expect(pool.drop(handle));
try std.testing.expect(pool.drop(handle));
}
try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations);
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(pool.slotCount(), pool.freeCount());
try std.testing.expect(pool.releaseAllFreeSlots());
const rebuilt = try pool.new(.{ .id = 99 });
try std.testing.expectEqual(@as(TestPool.Pool.SlotIndex, 0), rebuilt.index);
try std.testing.expectEqual(@as(TestPool.Pool.Generation, 1), rebuilt.generation);
}
test "ref pool reserves deferred drop and trim storage" {
var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var pool = try DeferredTestPool.initCapacity(allocatorState.allocator(), 8);
defer pool.deinit();
const allocationsAfterReserve = allocatorState.allocations;
var handles: [8]DeferredTestPool.Handle = undefined;
for (&handles, 0..) |*handle, i| {
handle.* = try pool.new(.{ .id = @intCast(i) });
try std.testing.expect(pool.pin(handle.*));
}
for (handles) |handle| {
try std.testing.expect(pool.drop(handle));
try std.testing.expect(pool.drop(handle));
}
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 8), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
try std.testing.expectEqual(@as(usize, 8), pool.trim());
try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations);
try std.testing.expectEqual(pool.slotCount(), pool.freeCount());
try std.testing.expect(pool.releaseAllFreeSlots());
}
test "ref pool reports immediate growth allocation failures" {
for (0..4) |failIndex| {
var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{
.fail_index = failIndex,
});
var pool = TestPool.init(failingState.allocator());
defer pool.deinit();
try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 }));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.slotCount());
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
}
}
test "ref pool reports deferred growth allocation failures" {
for (0..5) |failIndex| {
var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{
.fail_index = failIndex,
});
var pool = DeferredTestPool.init(failingState.allocator());
defer pool.deinit();
try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 }));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 0), pool.slotCount());
try std.testing.expectEqual(@as(usize, 0), pool.freeCount());
}
}
test "ref pool rejects capacity beyond its handle index range" {
var pool = DeferredTestPool.init(std.testing.allocator);
defer pool.deinit();
try std.testing.expectError(error.PoolFull, pool.ensureTotalCapacity(DeferredTestPool.maxSlotCount + 1));
try std.testing.expectEqual(@as(usize, 0), pool.count());
try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount());
try std.testing.expectEqual(@as(usize, 0), pool.slotCount());
}

View File

@ -0,0 +1,170 @@
const std = @import("std");
const string_pool = @import("string-pool.zig");
pub const RefString = string_pool.RefString;
pub fn RefStringMap(comptime T: type) type {
return struct {
const Self = @This();
const Map = std.StringHashMap(*Slot);
pub const Slot = struct {
payload: T,
stringRef: RefString,
};
pub const AddError = std.mem.Allocator.Error || error{
KeyAlreadyExists,
};
allocator: std.mem.Allocator,
map: Map,
pub fn init(allocator: std.mem.Allocator) Self {
return .{
.allocator = allocator,
.map = Map.init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.clearRetainingCapacity();
self.map.deinit();
}
pub fn deinitWithPayloadDeinit(self: *Self, comptime deinitPayload: fn (*T) void) void {
self.clearRetainingCapacityWithPayloadDeinit(deinitPayload);
self.map.deinit();
}
pub fn count(self: *const Self) usize {
return self.map.count();
}
pub fn contains(self: *const Self, key: RefString) bool {
return self.containsString(key.getUtf8());
}
pub fn containsString(self: *const Self, key: []const u8) bool {
return self.map.contains(key);
}
pub fn get(self: *const Self, key: RefString) ?*T {
return self.getString(key.getUtf8());
}
pub fn getString(self: *const Self, key: []const u8) ?*T {
const slot = self.map.get(key) orelse return null;
return &slot.payload;
}
pub fn getSlot(self: *const Self, key: RefString) ?*Slot {
return self.getSlotString(key.getUtf8());
}
pub fn getSlotString(self: *const Self, key: []const u8) ?*Slot {
return self.map.get(key);
}
pub fn add(self: *Self, key: RefString, payload: T) AddError!*T {
if (self.contains(key)) return error.KeyAlreadyExists;
const slot = try self.allocator.create(Slot);
errdefer self.allocator.destroy(slot);
slot.* = .{
.payload = payload,
.stringRef = key.pin(),
};
errdefer slot.stringRef.drop();
try self.map.putNoClobber(slot.stringRef.getUtf8(), slot);
return &slot.payload;
}
pub const putNoClobber = add;
pub fn remove(self: *Self, key: RefString) ?T {
return self.removeString(key.getUtf8());
}
pub fn removeString(self: *Self, key: []const u8) ?T {
const removed = self.map.fetchRemove(key) orelse return null;
const slot = removed.value;
const payload = slot.payload;
slot.stringRef.drop();
self.allocator.destroy(slot);
return payload;
}
pub fn clearRetainingCapacity(self: *Self) void {
var iter = self.map.valueIterator();
while (iter.next()) |slot_ptr| {
const slot = slot_ptr.*;
slot.stringRef.drop();
self.allocator.destroy(slot);
}
self.map.clearRetainingCapacity();
}
pub fn clearRetainingCapacityWithPayloadDeinit(self: *Self, comptime deinitPayload: fn (*T) void) void {
var iter = self.map.valueIterator();
while (iter.next()) |slot_ptr| {
const slot = slot_ptr.*;
deinitPayload(&slot.payload);
slot.stringRef.drop();
self.allocator.destroy(slot);
}
self.map.clearRetainingCapacity();
}
pub const ValueIterator = struct {
inner: Map.ValueIterator,
pub fn next(self: *@This()) ?*T {
const slot_ptr = self.inner.next() orelse return null;
return &slot_ptr.*.payload;
}
};
pub fn valueIterator(self: *const Self) ValueIterator {
return .{ .inner = self.map.valueIterator() };
}
pub const SlotIterator = struct {
inner: Map.ValueIterator,
pub fn next(self: *@This()) ?*Slot {
const slot_ptr = self.inner.next() orelse return null;
return slot_ptr.*;
}
};
pub fn slotIterator(self: *const Self) SlotIterator {
return .{ .inner = self.map.valueIterator() };
}
};
}
test "RefStringMap pins keys and removes payloads" {
try string_pool.setup(std.testing.allocator, std.testing.io);
defer string_pool.shutdown();
var map = RefStringMap(u32).init(std.testing.allocator);
defer map.deinit();
const key = try RefString.new("alpha");
const value = try map.add(key, 42);
key.drop();
try std.testing.expectEqual(@as(u32, 42), value.*);
try std.testing.expectEqual(@as(usize, 1), map.count());
try std.testing.expect(map.containsString("alpha"));
try std.testing.expectEqual(@as(u32, 42), map.getString("alpha").?.*);
const lookup = try RefString.new("alpha");
defer lookup.drop();
const removed = map.remove(lookup).?;
try std.testing.expectEqual(@as(u32, 42), removed);
try std.testing.expectEqual(@as(usize, 0), map.count());
}

View File

@ -0,0 +1,259 @@
const std = @import("std");
const stats = @import("stats.zig");
pub const RingQueueError = error{
QueueIsFull,
QueueIsEmpty,
AllocSizeTooSmall,
OutOfMemory,
};
// managed version of the ringqueue, includes a mutex
pub fn RingQueue(comptime T: type) type {
return struct {
const _InnerType = RingQueueU(T);
queue: _InnerType,
allocator: std.mem.Allocator,
io_context: std.Io,
mutex: std.Io.Mutex = .init,
pub fn init(allocator: std.mem.Allocator, io_context: std.Io, size: usize) !@This() {
const newSelf = @This(){
.queue = try _InnerType.init(allocator, size),
.allocator = allocator,
.io_context = io_context,
.mutex = .init,
};
return newSelf;
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
pub fn pushLocked(self: *@This(), newValue: T) RingQueueError!void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
try self.queue.push(newValue);
}
// only call this if you have locked already
pub fn popFromUnlocked(self: *@This()) ?T {
return self.queue.pop();
}
pub fn lock(self: *@This()) void {
self.mutex.lockUncancelable(self.io());
}
pub fn unlock(self: *@This()) void {
self.mutex.unlock(self.io());
}
pub fn popFromLocked(self: *@This()) ?T {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
const val = self.queue.pop();
return val;
}
pub fn allowRegrow(self: *@This()) void {
self.queue.allowRegrow();
}
pub fn count(self: @This()) usize {
return self.queue.count();
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return self.queue.getStatistics();
}
pub fn deinit(self: *@This()) void {
self.queue.deinit(self.allocator);
}
};
}
// tail points to next free
// head points to next one to read
// unmanaged ring queue
pub fn RingQueueU(comptime T: type) type {
return struct {
allocator: std.mem.Allocator = undefined,
buffer: []T = undefined,
head: usize = 0, // resets upon resizes
tail: usize = 0, // resets upon resizes
regrow_allowed: bool = false,
pub fn init(allocator: std.mem.Allocator, size: usize) !@This() {
const self = @This(){
.allocator = allocator,
.buffer = try allocator.alloc(T, size + 1),
};
return self;
}
pub fn allowRegrow(self: *@This()) void {
self.regrow_allowed = true;
}
fn growCapacity(self: *@This()) !void {
const current_capacity = self.capacity();
const new_capacity = if (current_capacity == 0) 1 else current_capacity * 2;
try self.resize(self.allocator, new_capacity);
}
pub fn push(self: *@This(), value: T) RingQueueError!void {
var next = (self.tail + 1) % self.buffer.len;
if (next == self.head) {
if (!self.regrow_allowed) {
return error.QueueIsFull;
}
try self.growCapacity();
next = (self.tail + 1) % self.buffer.len;
}
self.buffer[self.tail] = value;
self.tail = next;
}
pub fn pushFront(self: *@This(), value: T) !void {
var iHead = @as(isize, @intCast(self.head)) - 1;
if (iHead < 0) {
iHead = @as(isize, @intCast(self.buffer.len)) + iHead;
}
if (iHead == @as(isize, @intCast(self.tail))) {
if (!self.regrow_allowed) {
return error.QueueIsFull;
}
try self.growCapacity();
iHead = @as(isize, @intCast(self.buffer.len)) - 1;
}
self.head = @as(usize, @intCast(iHead));
self.buffer[self.head] = value;
}
pub fn count(self: @This()) usize {
if (self.head == self.tail)
return 0;
if (self.head < self.tail)
return self.tail - self.head;
// head > tail means we looped around.
return (self.buffer.len - self.head) + self.tail;
}
pub fn pop(self: *@This()) ?T {
if (self.head == self.tail)
return null;
const r = self.buffer[self.head];
self.head = ((self.head + 1) % self.buffer.len);
return r;
}
pub fn peek(self: *@This()) ?*T {
return self.at(0);
}
pub fn peekBack(self: @This()) ?*T {
return self.atBack(1);
}
// reference an element at an offset from the back of the queue
// similar to python's negative number syntax.
// gets you an element at an offset from the tail.
// given the way the tail works, this will return null on zero
pub fn atBack(self: @This(), offset: usize) ?*T {
const c = self.count();
if (offset > c or offset == 0) {
return null;
}
var x: isize = @as(isize, @intCast(self.tail)) - @as(isize, @intCast(offset));
if (x < 0) {
x = @as(isize, @intCast(self.buffer.len)) + x;
}
return &self.buffer[@as(usize, @intCast(x))];
}
pub fn at(self: *@This(), offset: usize) ?*T {
const c = self.count();
if (c == 0) {
return null;
}
if (offset >= c) {
return null;
}
const index = (self.head + offset) % self.buffer.len;
return &self.buffer[index];
}
// returns the number of elements this buffer can hold.
// you should rarely ever need to use this.
pub fn capacity(self: *@This()) usize {
return self.buffer.len - 1;
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return .{
.statName = "RingQueue",
.instanceCount = self.count(),
.memoryReserved = self.buffer.len * @sizeOf(T),
.memoryUsed = self.count() * @sizeOf(T),
};
}
pub fn resize(self: *@This(), allocator: std.mem.Allocator, size: usize) !void {
const c = self.count();
// new size needs to be greater than current size by 1, tail always points to an empty
if (c >= size) {
return error.AllocSizeTooSmall;
}
var buffer: []T = try allocator.alloc(T, size + 1);
var index: usize = 0;
while (self.pop()) |v| {
buffer[index] = v;
index += 1;
}
allocator.free(self.buffer);
self.buffer = buffer;
self.head = 0;
self.tail = index;
}
pub fn isEmpty(self: @This()) bool {
return self.head == self.tail;
}
pub fn empty(self: *@This()) void {
self.head = 0;
self.tail = 0;
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
allocator.free(self.buffer);
}
};
}

View File

@ -0,0 +1,33 @@
{
"attributes" : {
"target_uri": "mesh:/exopunk/guns/samplegun",
"magazine_uri": "mesh:/exopunk/guns/samplegun_magazine"
},
"materials" : [
{
"material_name" : "gun body",
"master" : "opaque",
"albedo" : "texture:/exopunk/guns/samplegun_albedo",
"triple" : "texture:/exopunk/guns/samplegun_triple"
},
{
"material_name" : "scope",
"master" : "transparent",
"albedo" : "texture:/exopunk/guns/samplegun_scope"
}
],
"sockets" : [
{
"name": "socket_muzzle",
"pos": [1, 2, 3]
},
{
"name": "socket_magazine",
"pos": [1, 2, 3]
},
{
"name": "socket_sights",
"pos": [1, 2, 3]
}
]
}

View File

@ -0,0 +1,293 @@
const std = @import("std");
const PagedVector = @import("paged-vector.zig").PagedVector;
pub const Span = struct {
start: u32,
size: u32,
pub fn end(self: @This()) u32 {
return self.start + self.size;
}
};
pub const SpanHandle = struct {
_index: i32 = 0,
};
pub const AllocatedSpan = struct {
handle: SpanHandle,
span: Span,
};
pub const MergedSpan = struct {
start: u32,
end: u32, // points to one-past-the-end, invalid to deref
index: u32,
next: ?*MergedSpan = null,
};
pub const MergedSpans = struct {
list: ?*MergedSpan,
free_list: ?*MergedSpan,
capacity: u32,
available: u32,
spans: PagedVector(MergedSpan),
pub fn init(allocator: std.mem.Allocator, capacity: u32) !@This() {
return .{
.list = null,
.free_list = null,
.spans = try PagedVector(MergedSpan).init(allocator),
.capacity = capacity,
.available = capacity,
};
}
pub fn allocate(self: *@This(), size: u32) !Span {
// 1. find the first gap that matches the size
// 2. create a span from that gap and call addSpan on it.
var newSpan: ?Span = null;
var predecessor: ?*MergedSpan = null;
if (self.list) |list| {
if (list.start >= size) {
newSpan = .{ .start = 0, .size = size };
} else {
var iter: ?*MergedSpan = list;
while (iter) |p| : (iter = p.next) {
const gapStart = p.end;
var gapSize = self.capacity - gapStart;
if (p.next) |_next| {
const next: *MergedSpan = _next;
gapSize = next.start - p.end;
}
if (gapSize >= size) {
predecessor = p;
newSpan = .{ .start = gapStart, .size = size };
break;
}
}
}
} else {
// handle special case where we are empty and nothing is used.
if (size <= self.capacity) {
newSpan = .{ .start = 0, .size = size };
}
}
if (newSpan) |n| {
try self.addSpan(n, predecessor);
return n;
}
return error.OutOfMemory;
}
pub fn addSpan(self: *@This(), span: Span, predecessor: ?*MergedSpan) !void {
// update stats
self.available -= span.size;
// if the predecessor is null, this is the first span that we have, just set it and move on.
if (predecessor) |p| {
// if we're touching the end of one span, grow that one.
if (p.end == span.start) {
p.end += span.size;
if (p.next) |next| {
if (next.start == span.start + span.size) {
// delete the next one and update predecessor's end to the next one
p.end = next.end;
p.next = next.next;
self.removeMergedSpan(next);
}
}
} else if (p.next) |next| {
// if we're touching the start of one span, grow that one
if (next.start == span.start + span.size) {
next.start = span.start;
}
} else {
// if neither, then, create a new
const newSpan = try self.createMergedSpan(.{
.start = span.start,
.end = span.start + span.size,
.next = p.next,
.index = 0,
});
p.next = newSpan;
}
} else if (self.list) |list| {
if (span.end() == list.start) {
list.start = span.start;
} else {
self.list = try self.createMergedSpan(.{
.start = span.start,
.end = span.end(),
.next = list,
.index = 0,
});
}
} else {
self.list = try self.createMergedSpan(.{
.start = span.start,
.end = span.end(),
.next = null,
.index = 0,
});
}
}
fn createMergedSpan(self: *@This(), value: MergedSpan) !*MergedSpan {
if (self.free_list) |node| {
self.free_list = node.next;
node.* = value;
return node;
}
const index = self.spans.len();
const node = try self.spans.appendAndGet(value);
node.index = @intCast(index);
return node;
}
fn removeMergedSpan(self: *@This(), remove: *MergedSpan) void {
remove.* = .{
.start = 0,
.end = 0,
.index = remove.index,
.next = self.free_list,
};
self.free_list = remove;
}
pub fn debugSpanCount(self: @This()) u32 {
var i: u32 = 0;
var iter = self.list;
while (iter) |p| : (iter = p.next) {
i += 1;
}
return i;
}
pub fn removeSpan(self: *@This(), span: Span) void {
if (span.size == 0) return;
const remove_start = span.start;
const remove_end = span.end();
var released: u32 = 0;
var predecessor: ?*MergedSpan = null;
var iter = self.list;
while (iter) |node| {
const next = node.next;
if (remove_end <= node.start) break;
if (remove_start >= node.end) {
predecessor = node;
iter = next;
continue;
}
const overlap_start = @max(remove_start, node.start);
const overlap_end = @min(remove_end, node.end);
if (overlap_end > overlap_start) {
released += overlap_end - overlap_start;
}
if (remove_start <= node.start and remove_end >= node.end) {
if (predecessor) |prev| {
prev.next = next;
} else {
self.list = next;
}
self.removeMergedSpan(node);
iter = next;
continue;
}
if (remove_start <= node.start) {
node.start = remove_end;
break;
}
if (remove_end >= node.end) {
node.end = remove_start;
predecessor = node;
iter = next;
continue;
}
const tail = self.createMergedSpan(.{
.start = remove_end,
.end = node.end,
.next = node.next,
.index = 0,
}) catch unreachable;
node.end = remove_start;
node.next = tail;
break;
}
self.available += released;
}
pub fn deinit(self: *@This()) void {
self.spans.deinit();
}
};
test "span allocation" {
const allocator = std.testing.allocator;
var spans = try MergedSpans.init(allocator, 4096);
defer spans.deinit();
const newSpan: Span = try spans.allocate(16);
try std.testing.expectEqual(0, newSpan.start);
try std.testing.expectEqual(16, newSpan.size);
const newSpan2: Span = try spans.allocate(16);
try std.testing.expectEqual(16, newSpan2.start);
try std.testing.expectEqual(16, newSpan2.start);
const newSpan3: Span = try spans.allocate(16);
try std.testing.expectEqual(32, newSpan3.start);
try std.testing.expectEqual(16, newSpan3.size);
try std.testing.expectEqual(spans.debugSpanCount(), 1);
const newSpan4: Span = try spans.allocate(16);
try std.testing.expectEqual(48, newSpan4.start);
try std.testing.expectEqual(16, newSpan4.size);
spans.removeSpan(.{ .start = 12, .size = 4 });
try std.testing.expectEqual(2, spans.debugSpanCount());
const newSpan5: Span = try spans.allocate(4);
try std.testing.expectEqual(12, newSpan5.start);
try std.testing.expectEqual(4, newSpan5.size);
try std.testing.expectEqual(1, spans.debugSpanCount());
spans.removeSpan(.{ .start = 12, .size = 1 });
spans.removeSpan(.{ .start = 14, .size = 1 });
try std.testing.expectEqual(3, spans.debugSpanCount());
_ = try spans.allocate(1);
_ = try spans.allocate(1);
try std.testing.expectEqual(1, spans.debugSpanCount());
const available_before_full_remove = spans.available;
spans.removeSpan(newSpan);
try std.testing.expectEqual(1, spans.debugSpanCount());
try std.testing.expectEqual(available_before_full_remove + newSpan.size, spans.available);
const reused_full_remove = try spans.allocate(newSpan.size);
try std.testing.expectEqual(newSpan.start, reused_full_remove.start);
try std.testing.expectEqual(newSpan.size, reused_full_remove.size);
}

View File

@ -0,0 +1,885 @@
const std = @import("std");
const stats = @import("stats.zig");
const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
// can be index by an 18 bit value, and 262144 of anything ought to be enough... right?
pub const DefaultSparseSize = 262144 / 2;
pub fn SparseSet(comptime T: type) type {
return SparseSetAdvanced(T, DefaultSparseSize);
}
pub const IndexType = u24;
pub const GenerationType = u7;
pub const SetHandle = packed struct(u32) {
index: IndexType = 0,
generation: GenerationType = 0,
alive: bool = false,
pub fn hash(self: @This()) u32 {
return @as(u32, @bitCast(self));
}
pub fn eql(self: @This(), other: @This()) bool {
return self.hash() == other.hash();
}
};
pub fn SparseMultiSet(comptime T: type) type {
return SparseMultiSetAdvanced(T, DefaultSparseSize);
}
pub const ContainerListener = struct {
ptr: *anyopaque,
onHandleRemoved: *const fn (*anyopaque, u32, SetHandle) void,
onHandleAdded: *const fn (*anyopaque, u32, SetHandle) void,
};
// works by converting a datastructure into an AOS type.
pub fn SparseMultiSetAdvanced(comptime T: type, comptime SparseSize: u32) type {
return struct {
pub const SetType = std.MultiArrayList(T);
pub const InnerType = T;
allocator: std.mem.Allocator,
denseIndices: ArrayListUnmanaged(SetHandle),
dense: SetType,
sparse: []SetHandle,
containerID: u32 = 0,
containerListener: ?ContainerListener = null,
opCount: u32 = 0,
pub const Field = SetType.Field;
pub const Slice = SetType.Slice;
pub const IsMultiset = true;
pub const StableReferences = false;
pub fn init(allocator: std.mem.Allocator) @This() {
var self = @This(){
.allocator = allocator,
.denseIndices = .empty,
.dense = .empty,
.sparse = allocator.alloc(SetHandle, SparseSize) catch unreachable,
};
for (self.sparse, 0..) |_, i| {
self.sparse[i] = .{ .generation = 0, .index = 0x0, .alive = false };
}
return self;
}
pub fn create(allocator: std.mem.Allocator) !*@This() {
const self = try allocator.create(@This());
self.* = init(allocator);
return self;
}
pub fn destroy(self: *@This()) void {
const allocator = self.allocator;
self.deinit();
allocator.destroy(self);
}
pub fn denseItems(self: *@This(), comptime field: Field) []FieldType(field) {
return self.dense.items(field);
}
pub fn deinit(self: *@This()) void {
self.dense.deinit(self.allocator);
self.denseIndices.deinit(self.allocator);
self.allocator.free(self.sparse);
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return .{
.statName = "SparseMultiSet",
.instanceCount = self.dense.len,
.memoryReserved = self.dense.capacity * @sizeOf(T) +
self.denseIndices.capacity * @sizeOf(SetHandle) +
self.sparse.len * @sizeOf(SetHandle),
.memoryUsed = self.dense.len * @sizeOf(T) +
self.denseIndices.items.len * @sizeOf(SetHandle) +
self.sparse.len * @sizeOf(SetHandle),
};
}
pub fn readDense(self: @This(), offset: usize, comptime field: Field) *const FieldType(field) {
return &self.dense.items(field)[offset];
}
pub fn getDense(self: *@This(), offset: usize, comptime field: Field) *FieldType(field) {
return &self.dense.items(field)[offset];
}
// ----- sparse set features -----
pub fn handleFromSparseIndex(self: @This(), sparseIndex: IndexType) SetHandle {
var handle: SetHandle = self.sparse[@as(usize, @intCast(sparseIndex))];
handle.index = sparseIndex;
return handle;
}
pub fn sparseToDense(self: @This(), handle: SetHandle) ?usize {
const denseHandle = self.sparse[@as(usize, @intCast(handle.index))];
// todo: need to update generation
if (denseHandle.generation != handle.generation) // tombstone value
{
// Generation mismatch, this handle is totally dead.
return null;
}
if (denseHandle.alive == false) {
return null;
}
const denseIndex = @as(usize, @intCast(denseHandle.index));
if (denseIndex >= self.denseIndices.items.len) {
return null;
}
return denseIndex;
}
pub fn FieldType(comptime field: Field) type {
return std.meta.fieldInfo(T, field).type;
}
pub fn get(self: *@This(), handle: SetHandle, comptime field: Field) ?*FieldType(field) {
const denseIndex = self.sparseToDense(handle) orelse return null;
return &self.dense.items(field)[denseIndex];
}
// the idea behind a sparse array is that the sethandle is
// highly stable.
// if this container is registered as part of an ECS, this is unsafe to call directly
pub fn createObject(self: *@This(), initValue: T) !SetHandle {
var newSparseIndex = newRandomIndex();
var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
while (denseHandle.alive == true) {
newSparseIndex = newRandomIndex();
denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
}
const generation = (denseHandle.generation + 1) % (std.math.maxInt(GenerationType));
return self.createObjectInternal(initValue, newSparseIndex, generation);
}
pub fn createObjectInternal(self: *@This(), initValue: T, newSparseIndex: IndexType, generation: GenerationType) !SetHandle {
const newDenseIndex = self.denseIndices.items.len;
self.sparse[@as(usize, @intCast(newSparseIndex))] = SetHandle{
.alive = true,
.generation = @as(GenerationType, @intCast(generation)),
.index = @as(IndexType, @intCast(newDenseIndex)),
};
const setHandle = SetHandle{
.alive = true,
.generation = generation,
.index = newSparseIndex,
};
try self.denseIndices.append(self.allocator, setHandle);
try self.dense.append(self.allocator, initValue);
std.debug.assert(self.sparse[newSparseIndex].index < self.dense.len);
self.opCount +%= 1;
if (self.containerListener) |l| {
l.onHandleAdded(l.ptr, @intCast(self.containerID), setHandle);
}
return setHandle;
}
pub fn denseToSparse(self: @This(), dense: u32) SetHandle {
return self.denseIndices.items[dense];
}
pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !SetHandle {
const currentDenseHandle = self.sparse[handle.index];
if (currentDenseHandle.alive) {
return error.ObjectAlreadyExists;
}
return self.createObjectInternal(initValue, handle.index, handle.generation);
}
pub fn destroyObject(self: *@This(), handle: SetHandle) bool {
// to destroy an object
// get handle and get the dense position, swap and remove.
// Then insert the tombstone value into the sparse handle
// if this fails it means the object is already destroyed
const denseIndex = self.sparseToDense(handle) orelse return false;
// get the indec of the last object in the dense set
const tailDenseIndex = self.dense.len - 1;
// get the sparse index of the last object
const sparseIndexToSwap = self.denseIndices.items[tailDenseIndex];
// redirect the sparse index to the new position of the swapped object.
self.sparse[@as(usize, @intCast(sparseIndexToSwap.index))].index = @as(IndexType, @intCast(denseIndex));
// perform the swap and remove, mark the tombstone as well.
_ = self.dense.swapRemove(denseIndex);
_ = self.denseIndices.swapRemove(denseIndex);
self.sparse[@as(usize, @intCast(handle.index))].alive = false;
self.opCount +%= 1;
if (self.containerListener) |l| {
l.onHandleRemoved(l.ptr, self.containerID, handle);
}
return true;
}
var prng = std.Random.DefaultPrng.init(0x1234);
var rand = prng.random();
pub fn newRandomIndex() IndexType {
if (SparseSize == std.math.maxInt(IndexType)) {
return rand.int(IndexType);
}
return rand.int(IndexType) % @as(IndexType, @intCast(SparseSize));
}
// ecs interface
pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This());
pub fn handleExists(self: @This(), handle: SetHandle) bool {
return self.sparseToDense(handle) != null;
}
pub fn getContainerID(self: @This()) u32 {
return self.containerID;
}
pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void {
self.containerID = id;
self.containerListener = listener;
}
pub fn evictFromRegistry(self: *@This()) void {
self.containerListener = null;
}
pub fn getStateCount(self: @This()) u32 {
return self.opCount;
}
// replaces get.
// really nasty trick here. I'm relying on absolutely fucked aliasing
// for sparse-multiset
// which is not a type which can be represented in lua directly.
// rather the resulting component type should be a THIN component
// which only contains the handle.
//
// Zig MAY break this in the future. in which case I'll have to
// treat the sparse sets in this handle as C ABI with a fixed bit layout
pub fn getHandleRef(self: @This(), handle: SetHandle) *SetHandle {
if (self.handleExists(handle)) {
// std.debug.print("get: {p}\n", .{@as(*anyopaque, @ptrCast(&self.sparse[handle.index]))});
return &self.sparse[handle.index];
}
@panic("uh oh ");
}
pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *SetHandle {
_ = self.createWithHandle(handle, .{}) catch @panic("unable to create with handle");
return self.getHandleRef(handle);
}
pub const ContainerTypeName = "SparseMultiSet";
};
}
// A quick little sparse set implementation, this feeds the core of the
// ECS. A sparse set provides Constant time random access to a range of objects through stable handles
// While providing dense memory locality for iterating.
//
// should probably never use this one outside of the base-set for checking entity existence.
pub fn SparseSetAdvanced(comptime T: type, comptime SparseSize: u32) type {
return struct {
const DenseEntry = struct {
value: T,
sparseIndex: SetHandle,
};
allocator: std.mem.Allocator,
dense: ArrayListUnmanaged(DenseEntry),
sparse: []SetHandle,
containerID: u32 = 0,
containerListener: ?ContainerListener = null,
opCount: u32 = 0,
pub const StableReferences = false;
pub const InnerType = T;
pub fn getStateCount(self: @This()) u32 {
return self.opCount;
}
pub fn handleFromSparseIndex(self: @This(), sparseIndex: IndexType) SetHandle {
var handle: SetHandle = self.sparse[@as(usize, @intCast(sparseIndex))];
handle.index = sparseIndex;
return handle;
}
pub fn create(allocator: std.mem.Allocator) !*@This() {
const self = try allocator.create(@This());
self.* = init(allocator);
return self;
}
pub fn destroy(self: *@This()) void {
self.deinit();
self.allocator.destroy(self);
}
pub fn init(allocator: std.mem.Allocator) @This() {
var self = @This(){
.allocator = allocator,
.dense = .empty,
.sparse = allocator.alloc(SetHandle, SparseSize) catch unreachable,
};
for (self.sparse, 0..) |_, i| {
self.sparse[i] = .{ .generation = 0, .index = 0x0, .alive = false };
}
return self;
}
pub fn readDense(self: @This(), offset: usize) *const T {
return &self.dense.items[offset].value;
}
pub fn getDense(self: *@This(), offset: usize) *T {
return &self.dense.items[offset].value;
}
pub fn count(self: @This()) usize {
return self.dense.items.len;
}
pub fn ensureUnusedCapacity(self: *@This(), additionalCount: usize) !void {
try self.dense.ensureUnusedCapacity(self.allocator, additionalCount);
}
pub fn sparseToDense(self: @This(), handle: SetHandle) ?usize {
const denseHandle = self.sparse[@as(usize, @intCast(handle.index))];
// todo: need to update generation
if (denseHandle.generation != handle.generation) // tombstone value
{
// Generation mismatch, this handle is totally dead.
return null;
}
if (denseHandle.alive == false) {
return null;
}
const denseIndex = @as(usize, @intCast(denseHandle.index));
if (denseIndex >= self.dense.items.len) {
return null;
}
return denseIndex;
}
pub fn get(self: @This(), handle: SetHandle) ?*T {
const denseIndex = self.sparseToDense(handle) orelse return null;
return &self.dense.items[denseIndex].value;
}
pub fn destroyObject(self: *@This(), handle: SetHandle) void {
// to destroy an object
// get handle and get the dense position, swap and remove.
// Then insert the tombstone value into the sparse handle
if (@hasDecl(T, "deinitECS")) {
self.get(handle).?.deinitECS(handle);
}
const denseIndex = self.sparseToDense(handle) orelse return;
const tailDenseIndex = self.dense.items.len - 1;
const sparseIndexToSwap = self.dense.items[tailDenseIndex].sparseIndex;
self.opCount +%= 1;
self.sparse[@as(usize, @intCast(sparseIndexToSwap.index))].index = @as(IndexType, @intCast(denseIndex));
_ = self.dense.swapRemove(denseIndex);
self.sparse[@as(usize, @intCast(handle.index))].alive = false;
if (self.containerListener) |l| {
l.onHandleRemoved(l.ptr, self.containerID, handle);
}
}
var prng = std.Random.DefaultPrng.init(0x1234);
var rand = prng.random();
fn newRandomIndex() IndexType {
if (SparseSize == std.math.maxInt(IndexType)) {
return rand.int(IndexType);
}
return rand.int(IndexType) % @as(IndexType, @intCast(SparseSize));
}
// the idea behind a sparse array is that the sethandle is
// highly stable.
pub fn createObject(self: *@This(), initValue: T) !SetHandle {
var newSparseIndex = newRandomIndex();
self.opCount +%= 1;
var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
while (denseHandle.alive == true) {
newSparseIndex = newRandomIndex();
denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
}
const generation = (denseHandle.generation + 1) % (std.math.maxInt(GenerationType));
const newDenseIndex = self.dense.items.len;
const sparseToDenseHandle = SetHandle{
.alive = true,
.generation = @as(GenerationType, @intCast(generation)),
.index = @as(IndexType, @intCast(newDenseIndex)),
};
const denseToSparseHandle = SetHandle{
.alive = true,
.generation = @as(GenerationType, @intCast(generation)),
.index = @as(IndexType, @intCast(newSparseIndex)),
};
try self.dense.append(self.allocator, .{
.value = initValue,
.sparseIndex = denseToSparseHandle,
});
self.sparse[@as(usize, @intCast(newSparseIndex))] = sparseToDenseHandle;
const setHandle = SetHandle{
.alive = true,
.generation = generation,
.index = newSparseIndex,
};
return setHandle;
}
pub const ConstructResult = struct {
ptr: *T,
handle: SetHandle,
};
// Will fail if the handle already exists.
pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !ConstructResult {
if (handle.index >= DefaultSparseSize) {
std.debug.print("this should never happen handle index is huge: {x} {d}\n", .{ handle.index, handle.index });
@panic("impossible handle");
}
var currentDenseHandle = self.sparse[handle.index];
if (currentDenseHandle.alive) {
return error.ObjectAlreadyExists;
}
currentDenseHandle.generation = handle.generation;
currentDenseHandle.alive = true;
return try self.createAndGetInternal(currentDenseHandle, handle.index, initValue, false);
}
pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *T {
const rv = (self.createWithHandle(handle, .{}) catch @panic("unable to create")).ptr;
if (@hasDecl(T, "initECS")) {
rv.initECS(handle);
}
return rv;
}
fn createAndGetInternal(self: *@This(), denseHandle: SetHandle, sparseIndex: IndexType, initValue: T, comptime bumpGeneration: bool) !ConstructResult {
const newDenseIndex = self.dense.items.len;
try self.dense.append(self.allocator, .{
.value = initValue,
.sparseIndex = .{
.index = sparseIndex,
.generation = denseHandle.generation,
.alive = true,
},
});
var generation = denseHandle.generation;
if (bumpGeneration) {
generation = (generation + 1) % (std.math.maxInt(GenerationType));
}
self.sparse[@as(usize, @intCast(sparseIndex))] = SetHandle{
.alive = true,
.generation = @as(GenerationType, @intCast(generation)),
.index = @as(IndexType, @intCast(newDenseIndex)),
};
const setHandle = SetHandle{
.alive = true,
.generation = generation,
.index = sparseIndex,
};
const rv = ConstructResult{
.ptr = &self.dense.items[@as(usize, @intCast(newDenseIndex))].value,
.handle = setHandle,
};
if (self.containerListener) |l| {
l.onHandleAdded(l.ptr, self.containerID, setHandle);
}
return rv;
}
pub fn createAndGet(self: *@This(), initValue: T) !ConstructResult {
var newSparseIndex = newRandomIndex();
var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
while (denseHandle.alive == true) {
newSparseIndex = newRandomIndex();
denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))];
}
return try self.createAndGetInternal(denseHandle, newSparseIndex, initValue, true);
}
pub fn deinit(self: *@This()) void {
self.allocator.free(self.sparse);
self.dense.deinit(self.allocator);
}
pub fn getStatistics(self: *const @This()) stats.PoolStatistics {
return .{
.statName = "SparseSet",
.instanceCount = self.dense.items.len,
.memoryReserved = self.dense.capacity * @sizeOf(DenseEntry) +
self.sparse.len * @sizeOf(SetHandle),
.memoryUsed = self.dense.items.len * @sizeOf(DenseEntry) +
self.sparse.len * @sizeOf(SetHandle),
};
}
pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This());
pub fn handleExists(self: @This(), handle: SetHandle) bool {
return self.sparseToDense(handle) != null;
}
pub fn getContainerID(self: @This()) u32 {
return self.containerID;
}
pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void {
self.containerID = id;
self.containerListener = listener;
}
// might never need to call this one...
pub fn evictFromRegistry(self: *@This()) void {
self.containerListener = null;
}
pub const ContainerTypeName = "SparseSet";
};
}
// slowish look-up, fast-ish iteration time,
// very little memory overhead, stable pointers
// good all-around choice if you have a small
// number of these objects around, and the object itself is quite big.
pub fn SparseMap(comptime T: type) type {
return struct {
backingAllocator: std.mem.Allocator,
arena: std.heap.ArenaAllocator,
map: std.AutoHashMapUnmanaged(SetHandle, *T) = .empty,
listEntriesByHandle: std.AutoHashMapUnmanaged(SetHandle, u32) = .empty,
list: std.ArrayListUnmanaged(*T) = .empty,
handles: std.ArrayListUnmanaged(SetHandle) = .empty,
containerID: u32 = 0,
containerListener: ?ContainerListener = null,
opCount: u32 = 0,
pub const InnerType = T;
pub const StableReferences = true;
pub fn create(backingAllocator: std.mem.Allocator) !*@This() {
const self = try backingAllocator.create(@This());
self.* = .{
.arena = std.heap.ArenaAllocator.init(backingAllocator),
.backingAllocator = backingAllocator,
};
return self;
}
pub fn indexToHandle(self: @This(), index: usize) SetHandle {
return self.handles.items[index];
}
pub fn destroyObject(self: *@This(), handle: SetHandle) void {
std.debug.assert(self.map.contains(handle));
if (@hasDecl(T, "deinitECS")) {
self.map.get(handle).?.deinitECS(handle);
}
const alloc = self.allocator();
const index = self.listEntriesByHandle.get(handle).?;
alloc.destroy(self.map.get(handle).?);
_ = self.map.remove(handle);
_ = self.listEntriesByHandle.remove(handle);
_ = self.list.swapRemove(index); // oops.
const swappedHandle = self.handles.getLastOrNull();
_ = self.handles.swapRemove(index);
if (swappedHandle) |swapped|
self.listEntriesByHandle.put(alloc, swapped, index) catch unreachable;
self.opCount +%= 1;
if (self.containerListener) |l| {
l.onHandleRemoved(l.ptr, self.containerID, handle);
}
}
pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !*T {
std.debug.assert(!self.map.contains(handle));
const alloc = self.allocator();
const new = try alloc.create(T);
new.* = initValue;
try self.map.put(alloc, handle, new);
try self.list.append(alloc, new);
try self.handles.append(alloc, handle);
try self.listEntriesByHandle.put(alloc, handle, @intCast(self.list.items.len - 1));
if (self.containerListener) |l| {
l.onHandleAdded(l.ptr, self.containerID, handle);
}
self.opCount +%= 1;
return new;
}
pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *T {
const rv = self.createWithHandle(handle, .{}) catch @panic("Unable to create");
if (@hasDecl(T, "initECS")) {
rv.initECS(handle);
}
return rv;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return self.arena.allocator();
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
// per-entry cost of each hashmap (key + value + metadata byte)
const mapEntryBytes = @sizeOf(SetHandle) + @sizeOf(*T) + 1;
const indexEntryBytes = @sizeOf(SetHandle) + @sizeOf(u32) + 1;
return .{
.statName = "SparseMap",
.instanceCount = self.list.items.len,
// values themselves are allocated out of the arena
.memoryReserved = self.arena.queryCapacity() +
self.map.capacity() * mapEntryBytes +
self.listEntriesByHandle.capacity() * indexEntryBytes +
self.list.capacity * @sizeOf(*T) +
self.handles.capacity * @sizeOf(SetHandle),
.memoryUsed = self.map.count() * mapEntryBytes +
self.listEntriesByHandle.count() * indexEntryBytes +
self.list.items.len * @sizeOf(*T) +
self.handles.items.len * @sizeOf(SetHandle),
};
}
pub fn destroy(self: *@This()) void {
self.arena.deinit();
self.backingAllocator.destroy(self);
}
// == interface below ==
pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This());
pub fn get(self: @This(), handle: SetHandle) ?*anyopaque {
return self.map.get(handle);
}
pub fn handleExists(self: @This(), handle: SetHandle) bool {
return self.map.contains(handle);
}
pub fn getContainerID(self: @This()) u32 {
return self.containerID;
}
pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void {
self.containerID = id;
self.containerListener = listener;
}
// might never need to call this one...
pub fn evictFromRegistry(self: *@This()) void {
self.containerListener = null;
}
pub fn getStateCount(self: @This()) u32 {
return self.opCount;
}
pub const ContainerTypeName = "SparseMap";
};
}
// this is quickly becoming the ecs containers file
// todo.. move EcsContainerInterface into somewhere else.
const interface = @import("interface.zig");
pub const EcsContainerInterface = interface.MakeInterface("EcsContainerInterfaceVTable", struct {
containerTypeName: []const u8,
componentName: []const u8,
handleExists: *const fn (*const anyopaque, SetHandle) bool,
get: *const fn (*const anyopaque, SetHandle) ?*anyopaque,
createWithHandle: *const fn (*anyopaque, SetHandle) *anyopaque,
destroyObject: *const fn (*anyopaque, SetHandle) void,
getContainerID: *const fn (*const anyopaque) u32,
onRegister: *const fn (*anyopaque, u32, ContainerListener) void,
evictFromRegistry: *const fn (*anyopaque) void,
getStateCount: *const fn (*anyopaque) u32, // returns an internal number representing the state of the container
pub const Reference = struct {
vtable: *const @This(),
ptr: *anyopaque,
};
pub fn Implement(comptime TargetType: type) @This() {
const Wrap = struct {
pub fn handleExists(p: *const anyopaque, handle: SetHandle) bool {
var ptr = @as(*const TargetType, @ptrCast(@alignCast(p)));
return ptr.handleExists(handle);
}
// gets a function. assuming it exists
pub fn get(p: *const anyopaque, handle: SetHandle) ?*anyopaque {
// std.debug.print("get {p}\n", .{p});
var ptr = @as(*const TargetType, @ptrCast(@alignCast(p)));
if (@hasDecl(TargetType, "getHandleRef")) {
return ptr.getHandleRef(handle);
}
return @ptrCast(ptr.get(handle));
}
pub fn destroyObject(p: *anyopaque, handle: SetHandle) void {
// std.debug.print("creat with handle {p}\n", .{p});
var ptr = @as(*TargetType, @ptrCast(@alignCast(p)));
ptr.destroyObject(handle);
}
pub fn createWithHandle(p: *anyopaque, handle: SetHandle) *anyopaque {
// std.debug.print("creat with handle {p}\n", .{p});
var ptr = @as(*TargetType, @ptrCast(@alignCast(p)));
return ptr.createWithHandleECS(handle);
}
pub fn getStateCount(p: *const anyopaque) u32 {
// std.debug.print("getstatecount {p}\n", .{p});
var ptr = @as(*const TargetType, @ptrCast(@alignCast(p)));
return ptr.getStateCount();
}
pub fn getContainerID(p: *const anyopaque) u32 {
var ptr = @as(*const TargetType, @ptrCast(@alignCast(p)));
return ptr.getContainerID();
}
pub fn onRegister(p: *anyopaque, id: u32, listener: ContainerListener) void {
var ptr = @as(*TargetType, @ptrCast(@alignCast(p)));
return ptr.onRegister(id, listener);
}
pub fn evictFromRegistry(p: *anyopaque) void {
var ptr = @as(*TargetType, @ptrCast(@alignCast(p)));
return ptr.evictFromRegistry();
}
};
return .{
.containerTypeName = TargetType.ContainerTypeName,
.componentName = @typeName(TargetType.InnerType),
.handleExists = Wrap.handleExists,
.get = Wrap.get,
.createWithHandle = Wrap.createWithHandle,
.destroyObject = Wrap.destroyObject,
.getContainerID = Wrap.getContainerID,
.onRegister = Wrap.onRegister,
.evictFromRegistry = Wrap.evictFromRegistry,
.getStateCount = Wrap.getStateCount,
};
}
});
test "sparse-multiset-recycle-handles" {
const testHandle: SetHandle = .{
.index = 420,
.alive = true,
.generation = 12,
};
const testHandle2: SetHandle = .{
.index = 421,
.alive = true,
.generation = 12,
};
const TestStruct = struct {
wutang: u32 = 0,
lmao: u32 = 0,
};
var testSet = SparseMultiSet(TestStruct).init(std.testing.allocator);
defer testSet.deinit();
_ = testSet.createWithHandleECS(testHandle);
_ = testSet.createWithHandleECS(testHandle2);
std.debug.assert(testSet.get(testHandle, .wutang) != null);
std.debug.assert(testSet.get(testHandle2, .wutang) != null);
}

View File

@ -0,0 +1,681 @@
const std = @import("std");
pub const PackedState = packed struct(u32) {
remaining_items: u24 = 0, // Unclaimed entries.
active_readers: u8 = 0, // Consumers copying descriptors.
};
pub const Config = struct {
ChunkSize: usize = 256,
};
/// Single-producer, multiple-consumer batch mailbox. Keep its address stable.
/// The producer pushes values then calls submit(). Each consumer supplies its
/// own [ChunkSize]T buffer to maybeTake() and processes the returned slice.
/// Empty slices mean no chunk is claimable. The final chunk may be shorter.
pub fn CommitQueue(comptime T: type, comptime config: Config) type {
if (config.ChunkSize == 0 or config.ChunkSize > std.math.maxInt(u24))
@compileError("ChunkSize must be between 1 and 16777215");
return struct {
pub const Item = T;
pub const ChunkSize = config.ChunkSize;
allocator: std.mem.Allocator,
state: std.atomic.Value(u32) = .init(0),
active: std.ArrayList(T) = .empty,
back: std.ArrayList(T) = .empty,
pub fn init(allocator: std.mem.Allocator) @This() {
return .{ .allocator = allocator };
}
pub fn deinit(self: *@This()) void {
while (!self.canSubmit()) std.atomic.spinLoopHint();
self.active.deinit(self.allocator);
self.back.deinit(self.allocator);
}
/// Producer only. Grows the private backbuffer as needed.
pub fn push(self: *@This(), item: T) !void {
if (self.back.items.len == std.math.maxInt(u24)) return error.BatchFull;
try self.back.append(self.allocator, item);
}
/// Copy up to ChunkSize values into consumer-owned storage. The returned
/// slice lives until that storage is overwritten, even across submit().
/// Empty/saturated batches return a static empty slice without touching output.
pub fn maybeTake(self: *@This(), output: *[ChunkSize]T) []const T {
var s: PackedState = @bitCast(self.state.load(.monotonic));
while (true) {
if (s.remaining_items == 0 or s.active_readers == std.math.maxInt(u8))
return &.{};
// Claim a contiguous chunk and pin its batch atomically.
var desired = s;
const count: u24 = @intCast(@min(@as(usize, s.remaining_items), ChunkSize));
desired.remaining_items -= count;
desired.active_readers += 1;
if (self.state.cmpxchgWeak(@bitCast(s), @bitCast(desired), .acquire, .monotonic)) |observed| {
s = @bitCast(observed);
continue;
}
// Read metadata only after successfully pinning.
const index = self.active.items.len - @as(usize, s.remaining_items);
@memcpy(output[0..count], self.active.items[index..][0..count]);
self.releaseReader();
return output[0..count];
}
}
/// Release a pin after copying the submission.
fn releaseReader(self: *@This()) void {
// Every caller owns a pin. Subtracting one high-byte unit cannot
// alter the low 24 bits, even while other consumers claim entries.
const previous = self.state.fetchSub(@as(u32, 1) << 24, .release);
std.debug.assert(@as(PackedState, @bitCast(previous)).active_readers != 0);
}
pub fn canSubmit(self: *const @This()) bool {
return self.state.load(.acquire) == 0;
}
/// Must only be called Producer only.
/// publishes the backbuffer to all consumers,
pub fn submit(self: *@This()) void {
while (!self.canSubmit()) {
std.atomic.spinLoopHint();
}
std.mem.swap(@TypeOf(self.active), &self.active, &self.back);
self.back.clearRetainingCapacity();
self.state.store(@bitCast(PackedState{ .remaining_items = @intCast(self.active.items.len) }), .release);
}
};
}
// Drain before deinit on assertion/OOM paths: deinit deliberately waits for
// outstanding submissions and would otherwise hide the original test failure.
fn drainTestQueue(queue: anytype) void {
var output: [@TypeOf(queue.*).ChunkSize]@TypeOf(queue.*).Item = undefined;
while (queue.maybeTake(&output).len != 0) {}
}
test "spmc publication is explicit and batches remain isolated during growth" {
var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
try std.testing.expect(queue.canSubmit());
try std.testing.expectEqual(null, takeTestOne(&queue));
for (0..8) |_| {
queue.submit();
try std.testing.expect(queue.canSubmit());
try std.testing.expectEqual(null, takeTestOne(&queue));
}
for (0..17) |i| try queue.push(i);
try std.testing.expectEqual(null, takeTestOne(&queue));
queue.submit();
try std.testing.expect(!queue.canSubmit());
// Force several backbuffer reallocations while the old front is live.
for (0..4097) |i| try queue.push(10000 + i);
for (0..17) |i| try std.testing.expectEqual(i, takeTestOne(&queue).?);
try std.testing.expect(queue.canSubmit());
try std.testing.expectEqual(null, takeTestOne(&queue));
queue.submit();
for (0..4097) |i| try std.testing.expectEqual(10000 + i, takeTestOne(&queue).?);
try std.testing.expectEqual(null, takeTestOne(&queue));
}
test "spmc repeated swaps preserve FIFO values without replaying stale capacity" {
const Item = struct { id: usize, bytes: [257]u8 };
var queue = CommitQueue(Item, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
const sizes = [_]usize{ 513, 0, 1, 0, 33, 2, 1025, 3 };
var next: usize = 0;
for (0..64) |round| {
const count = sizes[round % sizes.len];
for (0..count) |i| {
var item: Item = .{ .id = next + i, .bytes = @splat(@truncate(next + i)) };
try queue.push(item);
item.bytes = @splat(0); // push owns a value copy.
}
try std.testing.expectEqual(null, takeTestOne(&queue));
queue.submit();
for (0..count) |i| {
const item = takeTestOne(&queue).?;
try std.testing.expectEqual(next + i, item.id);
for (item.bytes) |byte| try std.testing.expectEqual(@as(u8, @truncate(next + i)), byte);
}
next += count;
try std.testing.expectEqual(null, takeTestOne(&queue));
try std.testing.expect(queue.canSubmit());
}
}
test "spmc flush requires both zero entries and zero reader pins" {
var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
// Synthetic states cover the interval after the last claim but before its
// copy finishes, which cannot be scheduled reliably through maybeTake alone.
for ([_]PackedState{
.{ .remaining_items = 1 },
.{ .active_readers = 1 },
.{ .remaining_items = 7, .active_readers = 3 },
.{ .active_readers = std.math.maxInt(u8) },
}) |state| {
storeTestState(&queue, state, .monotonic);
try std.testing.expect(!queue.canSubmit());
}
storeTestState(&queue, .{ .active_readers = 1 }, .monotonic);
try std.testing.expectEqual(null, takeTestOne(&queue));
queue.releaseReader();
try std.testing.expect(queue.canSubmit());
}
test "spmc saturated readers leave entries untouched and resume after release" {
var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
try queue.push(42);
queue.submit();
storeTestState(&queue, .{ .remaining_items = 1, .active_readers = 255 }, .monotonic);
try std.testing.expectEqual(null, takeTestOne(&queue));
try std.testing.expectEqual(@as(u24, 1), loadTestState(&queue).remaining_items);
try std.testing.expectEqual(@as(u8, 255), loadTestState(&queue).active_readers);
queue.releaseReader();
// Claiming uses the last available pin, then returns it after the copy.
try std.testing.expectEqual(@as(u32, 42), takeTestOne(&queue).?);
try std.testing.expectEqual(@as(u24, 0), loadTestState(&queue).remaining_items);
try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers);
try std.testing.expectEqual(null, takeTestOne(&queue));
try std.testing.expect(!queue.canSubmit());
}
test "spmc packed counters occupy exactly 32 bits without overlap" {
try std.testing.expectEqual(@as(usize, 4), @sizeOf(PackedState));
try std.testing.expectEqual(@as(usize, 32), @bitSizeOf(PackedState));
try std.testing.expectEqual(@as(usize, 4), @sizeOf(std.atomic.Value(u32)));
const entries: PackedState = .{ .remaining_items = std.math.maxInt(u24) };
const readers: PackedState = .{ .active_readers = std.math.maxInt(u8) };
try std.testing.expectEqual(@as(u32, 0x00ffffff), @as(u32, @bitCast(entries)));
try std.testing.expectEqual(@as(u32, 0xff000000), @as(u32, @bitCast(readers)));
}
test "spmc maximum batch publishes without truncation and rejects overflow" {
var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
const limit = std.math.maxInt(u24);
// Zero-sized values exercise the actual length boundary without a huge allocation.
try queue.back.resize(std.testing.allocator, limit - 1);
try queue.push({});
try std.testing.expectError(error.BatchFull, queue.push({}));
try std.testing.expectEqual(@as(usize, limit), queue.back.items.len);
queue.submit();
try std.testing.expectEqual(limit, loadTestState(&queue).remaining_items);
try std.testing.expect(takeTestOne(&queue) != null);
try std.testing.expectEqual(@as(u24, limit - 1), loadTestState(&queue).remaining_items);
try std.testing.expectEqual(@as(u8, 0), loadTestState(&queue).active_readers);
// Discard remaining synthetic work, then prove a rejected push did not poison reuse.
storeTestState(&queue, .{}, .monotonic);
try queue.push({});
queue.submit();
try std.testing.expect(takeTestOne(&queue) != null);
try std.testing.expectEqual(null, takeTestOne(&queue));
}
test "spmc failed backbuffer growth preserves both batches and permits retry" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(failing.allocator());
defer queue.deinit();
defer drainTestQueue(&queue);
try queue.push(99);
queue.submit();
try queue.push(0);
const capacity = queue.back.capacity;
for (1..capacity) |i| try queue.push(i);
failing.fail_index = failing.alloc_index;
try std.testing.expectError(error.OutOfMemory, queue.push(capacity));
try std.testing.expectEqual(capacity, queue.back.items.len);
try std.testing.expectEqual(@as(usize, 99), takeTestOne(&queue).?);
failing.fail_index = std.math.maxInt(usize);
try queue.push(capacity);
queue.submit();
for (0..capacity + 1) |i| try std.testing.expectEqual(i, takeTestOne(&queue).?);
}
fn allocationFailureScenario(allocator: std.mem.Allocator) !void {
var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
for (0..4) |round| {
for (0..129) |i| try queue.push(round * 129 + i);
drainTestQueue(&queue);
queue.submit();
}
}
test "spmc allocation failures release front and pending backbuffer storage" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationFailureScenario, .{});
}
const ContentionTest = struct {
const rounds = 256;
const sizes = [_]usize{ 0, 1, 255, 256, 257, 512, 10000, 7 };
const total = 32 * (1 + 255 + 256 + 257 + 512 + 10000 + 7);
const Item = struct { id: usize, words: [64]u64 };
const Queue = CommitQueue(Item, .{});
queue: *Queue,
start: *std.Io.Event,
stop: *std.atomic.Value(bool),
seen: [total]u64 = @splat(0),
wrapIds: bool = false,
lastId: ?usize = null,
corrupt: bool = false,
fn word(id: usize, lane: usize) u64 {
return (@as(u64, @intCast(id)) *% 0x9e3779b97f4a7c15) ^ (@as(u64, @intCast(lane)) *% 0xd6e8feb86659fd93);
}
fn consume(self: *@This()) void {
var output: [Queue.ChunkSize]Item = undefined;
self.start.waitUncancelable(std.testing.io);
while (!self.stop.load(.acquire)) {
const items = self.queue.maybeTake(&output);
for (items) |item| {
if (!self.wrapIds and item.id >= total) {
self.corrupt = true;
continue;
}
if (self.lastId) |last| {
if (item.id <= last) self.corrupt = true;
}
self.lastId = item.id;
self.seen[item.id % total] +|= 1;
for (item.words, 0..) |value, lane| {
if (value != word(item.id, lane)) self.corrupt = true;
}
if (item.id % 17 == 0) std.Thread.yield() catch {};
}
if (items.len == 0) std.Thread.yield() catch {};
}
}
fn awaitDrained(queue: *Queue) !void {
const begin = std.Io.Timestamp.now(std.testing.io, .awake);
while (!queue.canSubmit()) {
if (begin.durationTo(std.Io.Timestamp.now(std.testing.io, .awake)).toMilliseconds() > 10000)
return error.QueueDrainTimeout;
std.Thread.yield() catch {};
}
}
};
test "spmc eight consumers deliver every large descriptor exactly once across 256 batches" {
const C = ContentionTest;
var queue = C.Queue.init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
var start: std.Io.Event = .unset;
var stop: std.atomic.Value(bool) = .init(false);
const workers = try std.testing.allocator.alloc(C, 8);
defer std.testing.allocator.free(workers);
var threads: [8]std.Thread = undefined;
var spawned: usize = 0;
{
// Also releases/joins a partially spawned set on allocation or spawn failure.
defer {
stop.store(true, .release);
start.set(std.testing.io);
for (threads[0..spawned]) |thread| thread.join();
}
for (workers, 0..) |*worker, i| {
worker.* = .{ .queue = &queue, .start = &start, .stop = &stop };
threads[i] = try std.Thread.spawn(.{}, C.consume, .{worker});
spawned += 1;
}
start.set(std.testing.io);
var next: usize = 0;
for (0..C.rounds) |round| {
// Build the next batch while consumers can still copy the previous one.
for (0..C.sizes[round % C.sizes.len]) |_| {
var item: C.Item = .{ .id = next, .words = undefined };
for (&item.words, 0..) |*value, lane| value.* = C.word(next, lane);
try queue.push(item);
next += 1;
}
try C.awaitDrained(&queue);
queue.submit();
}
try C.awaitDrained(&queue);
try std.testing.expectEqual(C.total, next);
}
// Per-worker observations avoid adding synchronization to descriptor copying.
for (workers) |*worker| try std.testing.expect(!worker.corrupt);
for (0..C.total) |id| {
var copies: u64 = 0;
for (workers) |*worker| copies += worker.seen[id];
try std.testing.expectEqual(@as(u64, 1), copies);
}
var emptyOutput: [C.Queue.ChunkSize]C.Item = undefined;
try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&emptyOutput).len);
try std.testing.expect(queue.canSubmit());
}
test "spmc zero sized values still consume exactly one claim each" {
var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
for ([_]usize{ 0, 1, 127, 0, 3 }) |count| {
for (0..count) |_| try queue.push({});
try std.testing.expectEqual(null, takeTestOne(&queue));
queue.submit();
for (0..count) |_| try std.testing.expect(takeTestOne(&queue) != null);
try std.testing.expectEqual(null, takeTestOne(&queue));
try std.testing.expect(queue.canSubmit());
}
}
test "spmc warmed buffers reuse capacity with all further allocations disabled" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(failing.allocator());
defer queue.deinit();
defer drainTestQueue(&queue);
// Both buffers must grow once before steady-state swaps need no allocation.
for (0..2) |_| {
for (0..129) |i| try queue.push(i);
queue.submit();
drainTestQueue(&queue);
}
const allocations = failing.alloc_index;
failing.fail_index = allocations;
for (0..64) |round| {
const count: usize = if (round % 3 == 0) 0 else 129;
for (0..count) |i| try queue.push(round * 129 + i);
queue.submit();
for (0..count) |i| try std.testing.expectEqual(round * 129 + i, takeTestOne(&queue).?);
try std.testing.expectEqual(null, takeTestOne(&queue));
}
try std.testing.expectEqual(allocations, failing.alloc_index);
}
fn testBlockedSubmit(comptime pinned: bool) !void {
const Producer = struct {
queue: *CommitQueue(u32, .{ .ChunkSize = 1 }),
entered: std.Io.Event = .unset,
finished: std.Io.Event = .unset,
fn run(self: *@This()) void {
self.entered.set(std.testing.io);
self.queue.submit();
self.finished.set(std.testing.io);
}
};
var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
try queue.push(11);
queue.submit();
try queue.push(22);
if (pinned) {
// Model the final consumer having claimed, but not yet copied, item 11.
storeTestState(&queue, .{ .active_readers = 1 }, .monotonic);
}
var producer: Producer = .{ .queue = &queue };
const thread = std.Thread.spawn(.{}, Producer.run, .{&producer}) catch |err| {
storeTestState(&queue, .{}, .monotonic);
return err;
};
defer {
// On a failed assertion unblock submit before joining. No consumer is
// running here, and both buffers are freed only after the producer exits.
storeTestState(&queue, .{}, .release);
thread.join();
}
try producer.entered.waitTimeout(std.testing.io, .{ .duration = .{
.raw = .fromSeconds(10),
.clock = .awake,
} });
// This observation window supplements the deterministic state tests above;
// the scheduler cannot guarantee that the producer ran inside the window.
try std.testing.expectError(error.Timeout, producer.finished.waitTimeout(std.testing.io, .{ .duration = .{
.raw = .fromMilliseconds(20),
.clock = .awake,
} }));
if (pinned) {
try std.testing.expectEqual(@as(u32, 11), queue.active.items[0]);
queue.releaseReader();
} else {
try std.testing.expectEqual(@as(u32, 11), takeTestOne(&queue).?);
}
try producer.finished.waitTimeout(std.testing.io, .{ .duration = .{
.raw = .fromSeconds(10),
.clock = .awake,
} });
try std.testing.expectEqual(@as(u32, 22), takeTestOne(&queue).?);
try std.testing.expectEqual(null, takeTestOne(&queue));
try std.testing.expect(queue.canSubmit());
}
test "spmc submit waits for the previous batch to be claimed" {
try testBlockedSubmit(false);
}
test "spmc submit waits for the last descriptor copy to release its pin" {
try testBlockedSubmit(true);
}
test "spmc stress 30 seconds of continuous publication with eight consumers" {
const C = ContentionTest;
var queue = C.Queue.init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
var start: std.Io.Event = .unset;
var stop: std.atomic.Value(bool) = .init(false);
const workers = try std.testing.allocator.alloc(C, 8);
defer std.testing.allocator.free(workers);
var threads: [8]std.Thread = undefined;
var spawned: usize = 0;
var next: usize = 0;
var batches: usize = 0;
{
defer {
stop.store(true, .release);
start.set(std.testing.io);
for (threads[0..spawned]) |thread| thread.join();
}
for (workers, 0..) |*worker, i| {
worker.* = .{ .queue = &queue, .start = &start, .stop = &stop, .wrapIds = true };
threads[i] = try std.Thread.spawn(.{}, C.consume, .{worker});
spawned += 1;
}
var random = std.Random.DefaultPrng.init(0x5a17_c0de);
const begin = std.Io.Timestamp.now(std.testing.io, .awake);
start.set(std.testing.io);
while (begin.durationTo(std.Io.Timestamp.now(std.testing.io, .awake)).toMilliseconds() < 30000) {
// Include empty publications and singleton races, plus batches large
// enough to keep all consumers busy and force backbuffer growth.
const count = random.random().uintAtMost(usize, 10000);
for (0..count) |_| {
var item: C.Item = .{ .id = next, .words = undefined };
for (&item.words, 0..) |*value, lane| value.* = C.word(next, lane);
try queue.push(item);
next += 1;
}
try C.awaitDrained(&queue);
queue.submit();
batches += 1;
}
try C.awaitDrained(&queue);
}
try std.testing.expect(batches > 1);
try std.testing.expect(next > 0);
for (workers) |*worker| try std.testing.expect(!worker.corrupt);
// A bounded histogram checks delivery counts over an unbounded ID stream.
// Strictly increasing IDs per consumer additionally detect local replay;
// the short stress test above tracks every individual descriptor exactly.
var received: u64 = 0;
for (0..C.total) |slot| {
var copies: u64 = 0;
for (workers) |*worker| copies += worker.seen[slot];
const expected = next / C.total + @intFromBool(slot < next % C.total);
try std.testing.expectEqual(@as(u64, @intCast(expected)), copies);
received += copies;
}
try std.testing.expectEqual(@as(u64, @intCast(next)), received);
var emptyOutput: [C.Queue.ChunkSize]C.Item = undefined;
try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&emptyOutput).len);
try std.testing.expect(queue.canSubmit());
std.debug.print("\nspmc 30s stress: {d} batches, {d} descriptors, 8 consumers\n", .{ batches, received });
}
fn storeTestState(queue: anytype, state: PackedState, comptime order: std.builtin.AtomicOrder) void {
queue.state.store(@bitCast(state), order);
}
fn loadTestState(queue: anytype) PackedState {
return @bitCast(queue.state.load(.monotonic));
}
test "spmc reader subtraction preserves every entry boundary for all pin counts" {
var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
for ([_]u24{ 0, 1, 0xffff, std.math.maxInt(u24) }) |remaining| {
for (1..256) |readers| {
storeTestState(&queue, .{ .remaining_items = remaining, .active_readers = @intCast(readers) }, .monotonic);
queue.releaseReader();
const observed = loadTestState(&queue);
try std.testing.expectEqual(remaining, observed.remaining_items);
try std.testing.expectEqual(@as(u8, @intCast(readers - 1)), observed.active_readers);
try std.testing.expectEqual(remaining == 0 and readers == 1, queue.canSubmit());
}
}
}
test "spmc simultaneous reader releases lose no decrements or unclaimed entries" {
const Worker = struct {
fn run(queue: *CommitQueue(void, .{ .ChunkSize = 1 }), gate: *std.Io.Event) void {
gate.waitUncancelable(std.testing.io);
for (0..31) |_| queue.releaseReader();
}
};
var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
storeTestState(&queue, .{ .remaining_items = std.math.maxInt(u24), .active_readers = 248 }, .monotonic);
var gate: std.Io.Event = .unset;
var threads: [8]std.Thread = undefined;
var spawned: usize = 0;
{
defer {
gate.set(std.testing.io);
for (threads[0..spawned]) |thread| thread.join();
}
for (&threads) |*thread| {
thread.* = try std.Thread.spawn(.{}, Worker.run, .{ &queue, &gate });
spawned += 1;
}
}
const observed = loadTestState(&queue);
try std.testing.expectEqual(@as(u24, std.math.maxInt(u24)), observed.remaining_items);
try std.testing.expectEqual(@as(u8, 0), observed.active_readers);
try std.testing.expect(!queue.canSubmit());
}
// Retain the original one-item behavioral tests using the chunk-size-one configuration.
fn takeTestOne(queue: anytype) ?@TypeOf(queue.*).Item {
const Q = @TypeOf(queue.*);
if (Q.ChunkSize != 1) @compileError("single-item test requires ChunkSize = 1");
var output: [1]Q.Item = undefined;
const items = queue.maybeTake(&output);
return if (items.len == 0) null else items[0];
}
test "spmc 256 item chunks preserve FIFO tails output bounds and copy lifetime" {
const Q = CommitQueue(usize, .{});
var queue = Q.init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
var output: [Q.ChunkSize]usize = @splat(std.math.maxInt(usize));
const empty = queue.maybeTake(&output);
try std.testing.expectEqual(@as(usize, 0), empty.len);
try std.testing.expect(empty.ptr != output[0..].ptr);
for (output) |value| try std.testing.expectEqual(std.math.maxInt(usize), value);
for ([_]usize{ 1, 255, 256, 257, 512, 519, 10000 }) |count| {
for (0..count) |i| try queue.push(i);
try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len);
queue.submit();
var offset: usize = 0;
while (offset < count) {
@memset(&output, std.math.maxInt(usize));
const items = queue.maybeTake(&output);
const expected = @min(Q.ChunkSize, count - offset);
try std.testing.expectEqual(expected, items.len);
try std.testing.expect(items.ptr == output[0..].ptr);
for (items, 0..) |item, i| try std.testing.expectEqual(offset + i, item);
for (output[expected..]) |value| try std.testing.expectEqual(std.math.maxInt(usize), value);
offset += expected;
try std.testing.expectEqual(@as(u24, @intCast(count - offset)), loadTestState(&queue).remaining_items);
try std.testing.expectEqual(@as(u8, 0), loadTestState(&queue).active_readers);
}
// Recycle both queue buffers without touching the consumer's copy.
const lastFirst = output[0];
queue.submit();
try queue.push(999999);
queue.submit();
try std.testing.expectEqual(lastFirst, output[0]);
drainTestQueue(&queue);
}
}
test "spmc chunk saturation rejects atomically then claims a full chunk with one pin" {
const Q = CommitQueue(u32, .{});
var queue = Q.init(std.testing.allocator);
defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic);
for (0..257) |i| try queue.push(@intCast(i));
queue.submit();
var output: [Q.ChunkSize]u32 = @splat(77);
storeTestState(&queue, .{ .remaining_items = 257, .active_readers = 255 }, .monotonic);
try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len);
try std.testing.expectEqual(@as(u24, 257), loadTestState(&queue).remaining_items);
for (output) |value| try std.testing.expectEqual(@as(u32, 77), value);
queue.releaseReader();
const items = queue.maybeTake(&output);
try std.testing.expectEqual(@as(usize, 256), items.len);
for (items, 0..) |value, i| try std.testing.expectEqual(@as(u32, @intCast(i)), value);
try std.testing.expectEqual(@as(u24, 1), loadTestState(&queue).remaining_items);
try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers);
const tail = queue.maybeTake(&output);
try std.testing.expectEqual(@as(usize, 1), tail.len);
try std.testing.expectEqual(@as(u32, 256), tail[0]);
try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers);
}
test "spmc configurable chunk sizes support zero sized values and short final chunks" {
inline for (.{ 1, 3, 256, 1024 }) |size| {
const Q = CommitQueue(void, .{ .ChunkSize = size });
var queue = Q.init(std.testing.allocator);
defer queue.deinit();
defer drainTestQueue(&queue);
var output: [Q.ChunkSize]void = undefined;
for (0..size * 2 + 1) |_| try queue.push({});
queue.submit();
try std.testing.expectEqual(@as(usize, size), queue.maybeTake(&output).len);
try std.testing.expectEqual(@as(usize, size), queue.maybeTake(&output).len);
try std.testing.expectEqual(@as(usize, 1), queue.maybeTake(&output).len);
try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len);
try std.testing.expect(queue.canSubmit());
}
}

View File

@ -0,0 +1,70 @@
const std = @import("std");
fn makeSlice(comptime T: type, ptr: *T, len: usize) []T {
var slice: []T = undefined;
slice.len = len;
slice.ptr = ptr;
return slice;
}
// A completely static arraylist, returns out of capacity when it's full.
// does NOT do any kind of allocator backing.
pub fn StaticVector(comptime T: type, comptime size: usize) type {
return struct {
fn makeEmptySlice() []T {
var slice: []T = undefined;
slice.len = 0;
slice.ptr = undefined;
return slice;
}
_data: [size]T = undefined,
items: []T = makeEmptySlice(),
pub fn append(self: *@This(), value: T) !void {
if (self.items.len >= size)
return error.OutOfCapacity;
self._data[self.items.len] = value;
self.items.ptr = @ptrCast(&self._data[0]);
self.items.len += 1;
}
pub fn pop(self: *@This()) ?T {
if (self.len == 0) {
return null;
}
self.items.len -= 1;
return self._data[self.len];
}
};
}
test "static vector" {
var al = StaticVector(struct { x: u32 = 0 }, 42){};
for (0..42) |i| {
try al.append(.{ .x = @intCast(i) });
}
std.debug.assert(al.items[0].x == 0);
std.debug.assert(al.items[1].x == 1);
} //
// TODO:
//
// this is a fixed size vector which
// exists on the stack until it exceeds the static capacity.
// in which case it gets bumped to the heap with an allocator.
pub fn SmallVectorUnmanaged(comptime T: type, comptime size: usize) type {
return struct {
data: [size]T = undefined,
ptr: *T = undefined,
len: usize = 0,
pub fn append(self: *@This()) !void {
_ = self;
}
};
}

View File

@ -0,0 +1,6 @@
pub const PoolStatistics = struct {
statName: []const u8,
instanceCount: usize,
memoryReserved: usize,
memoryUsed: usize,
};

View File

@ -0,0 +1,832 @@
const std = @import("std");
const stats = @import("stats.zig");
// main purpose of this string-pool is to provide an RC-able interface for
// interfacing with GC'ed systems such as lua
//
// Design: strings are immutable after creation. All "mutation" operations
// (append, trim, fmt, etc.) allocate a new string and drop the old handle.
// A generation counter per slot detects use-after-free of stale handles.
pub var gStringContext: *StringContext = undefined;
pub const RefString = struct {
index: u24,
bucketId: u8,
generation: u8 = 0,
pub fn getUtf8(self: @This()) []u8 {
return gStringContext.getUtf8(self);
}
pub const utf8 = getUtf8;
// creates a new string from []const u8
pub fn new(str: []const u8) !@This() {
return try gStringContext.newFromUtf8(str);
}
// deep copy of a string
pub fn clone(self: @This()) !@This() {
return try gStringContext.newFromUtf8(self.getUtf8());
}
// increases the reference count for this string by one and makes a copy of the handle
pub fn pin(self: @This()) @This() {
gStringContext.rcAdd(self);
return self;
}
pub fn drop(self: @This()) void {
gStringContext.strDestroy(self);
}
pub fn len(self: @This()) usize {
return gStringContext.handleLen(self);
}
pub fn concat(self: @This(), other: @This()) !@This() {
return try RefString.concatSlices(self.getUtf8(), other.getUtf8());
}
pub fn concatSlice(self: @This(), other: []const u8) !@This() {
return try RefString.concatSlices(self.getUtf8(), other);
}
pub fn concatSlices(left: []const u8, right: []const u8) !@This() {
return try gStringContext.newFromUtf8Concat(left, right);
}
pub fn append(self: @This(), other: []const u8) !@This() {
const result = try self.concatSlice(other);
self.drop();
return result;
}
pub const add = append;
pub fn trim(self: @This()) !@This() {
const str = self.getUtf8();
const trimmed = std.mem.trim(u8, str, " \t\n\r");
if (trimmed.len == str.len) {
return self.pin();
}
return try RefString.new(trimmed);
}
pub fn substring(self: @This(), start: usize, end: usize) !@This() {
const str = self.getUtf8();
const s = @min(start, str.len);
const e = @min(end, str.len);
return try RefString.new(str[s..e]);
}
pub fn substringSlice(self: @This(), start: usize, end: usize) []const u8 {
const str = self.getUtf8();
const s = @min(start, str.len);
const e = @min(end, str.len);
return str[s..e];
}
pub const SplitResult = struct {
items: []RefString,
pub fn deinit(self: @This()) void {
for (self.items) |s| s.drop();
gStringContext.getAllocator().free(self.items);
}
};
pub fn split(self: @This(), delimiter: []const u8) !SplitResult {
const str = self.getUtf8();
const allocator = gStringContext.getAllocator();
// count segments
var count: usize = 0;
var countIter = std.mem.splitSequence(u8, str, delimiter);
while (countIter.next()) |_| count += 1;
const items = try allocator.alloc(RefString, count);
errdefer allocator.free(items);
var iter = std.mem.splitSequence(u8, str, delimiter);
var i: usize = 0;
while (iter.next()) |segment| {
items[i] = try RefString.new(segment);
i += 1;
}
return .{ .items = items };
}
pub fn splitSlice(self: @This(), delimiter: []const u8) std.mem.SplitIterator(u8, .sequence) {
return std.mem.splitSequence(u8, self.getUtf8(), delimiter);
}
pub fn fmt(comptime format: []const u8, args: anytype) !@This() {
var buf: [4096]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try w.print(format, args);
const result = w.buffered();
return try RefString.new(result);
}
pub fn eql(self: @This(), other: @This()) bool {
if (self.bucketId == other.bucketId and self.index == other.index and self.generation == other.generation) return true;
return std.mem.eql(u8, self.getUtf8(), other.getUtf8());
}
pub fn eqlSlice(self: @This(), other: []const u8) bool {
return std.mem.eql(u8, self.getUtf8(), other);
}
};
pub const RefBuffer = RefString;
const StringAllocation = struct {
ptr: *align(4) anyopaque,
pub const HeaderLen = 6;
// offsets:
// 0x0 -> 0x4 : length (u32)
// 0x4 : reference count (u8, atomic)
// 0x5 : generation (u8, atomic)
// 0x6 -> : string content
pub fn len(self: @This()) usize {
const read = @as(*u32, @ptrCast(@alignCast(self.ptr))).*;
return @intCast(read);
}
pub fn setLen(self: @This(), length: usize) void {
@as(*u32, @ptrCast(@alignCast(self.ptr))).* = @intCast(length);
}
pub fn initRc(self: @This()) void {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
x[4] = std.atomic.Value(u8).init(1);
}
pub fn rcAdd(self: @This()) void {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
_ = x[4].fetchAdd(1, .monotonic);
}
// returns true if the reference count hits 0
pub fn rcSub(self: @This()) bool {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
if (x[4].fetchSub(1, .release) == 1) {
return true;
}
return false;
}
pub fn rc(self: @This()) u8 {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
return x[4].load(.monotonic);
}
pub fn generation(self: @This()) u8 {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
return x[5].load(.monotonic);
}
pub fn initGeneration(self: @This(), gen: u8) void {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
x[5] = std.atomic.Value(u8).init(gen);
}
pub fn bumpGeneration(self: @This()) void {
const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr);
_ = x[5].fetchAdd(1, .monotonic);
}
pub fn bytes(self: @This()) []u8 {
return @as([*]u8, @ptrCast(self.ptr))[HeaderLen .. HeaderLen + self.len()];
}
pub fn deallocBytes(self: @This()) []align(4) u8 {
var rv: []align(4) u8 = undefined;
rv.ptr = @ptrCast(self.ptr);
rv.len = self.len() + StringAllocation.HeaderLen;
return rv;
}
pub fn fromPtr(ptr: *anyopaque) @This() {
return .{ .ptr = @ptrCast(@alignCast(ptr)) };
}
};
const Page = struct {
bytes: []align(8) u8,
};
const Bucket = struct {
id: u32,
allocSize: u32,
io_context: std.Io,
pageSize: u32,
slotsPerPage: u32,
next: u32 = 0,
pages: std.ArrayListUnmanaged(Page) = .empty,
freeSlots: std.ArrayListUnmanaged(u32) = .empty,
lock: std.Io.Mutex = .init,
pub const BucketAllocation = struct {
bytes: []u8,
index: u24,
};
pub fn init(id: u32, allocSize: u32, pageSize: u32, io_context: std.Io) @This() {
return .{
.id = id,
.allocSize = allocSize,
.io_context = io_context,
.pageSize = pageSize,
.slotsPerPage = pageSize / allocSize,
};
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
// index to page
inline fn i2p(self: @This(), index: u32) u32 {
return @divFloor(index, self.slotsPerPage);
}
// index based off of a page
inline fn ibp(self: @This(), index: u32) u32 {
return index % self.slotsPerPage;
}
fn getBytesFromIndex(self: @This(), index: u32) []u8 {
return self.indexToSlot(self.i2p(index), self.ibp(index));
}
fn addPage(self: *@This(), allocator: std.mem.Allocator) !void {
const page: Page = .{
.bytes = try allocator.alignedAlloc(u8, .@"8", self.pageSize),
};
try self.pages.append(allocator, page);
}
fn indexToSlot(self: @This(), pageIndex: u32, pageBase: u32) []u8 {
const left = pageBase * self.allocSize;
const right = left + self.allocSize;
const slice = self.pages.items[pageIndex].bytes[left..right];
return slice;
}
pub fn destroySlot(self: *@This(), allocator: std.mem.Allocator, index: u32) void {
self.lock.lockUncancelable(self.io());
defer self.lock.unlock(self.io());
// bump generation so stale handles are detected on reuse
const alloc = StringAllocation.fromPtr(self.getBytesFromIndex(index).ptr);
alloc.bumpGeneration();
self.freeSlots.append(allocator, index) catch unreachable;
}
pub fn assignOrRecycleSlot(self: *@This(), allocator: std.mem.Allocator) !BucketAllocation {
self.lock.lockUncancelable(self.io());
defer self.lock.unlock(self.io());
if (self.freeSlots.items.len < 1) {
const pageIndex = self.i2p(self.next);
if (pageIndex >= self.pages.items.len) {
try self.addPage(allocator);
}
const rv: BucketAllocation = .{
.bytes = self.indexToSlot(pageIndex, self.ibp(self.next)),
.index = @intCast(self.next),
};
self.next += 1;
return rv;
} else {
const index = self.freeSlots.pop().?;
const rv: BucketAllocation = .{
.bytes = self.indexToSlot(self.i2p(index), self.ibp(index)),
.index = @intCast(index),
};
return rv;
}
}
};
pub const StringContext = struct {
backingAllocator: std.mem.Allocator,
io_context: std.Io,
arena: std.heap.ArenaAllocator,
buckets: std.ArrayListUnmanaged(Bucket) = .empty,
live_count: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
warning_fired: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
/// When the number of live pooled strings reaches this count, a warning is
/// logged once and `on_allocation_count_warning` is invoked (first hit only).
/// Lives on the context so it persists across hot reloads.
allocation_count_warning_threshold: usize = 1 << 20,
/// Invoked once, the first time the live allocation count reaches
/// `allocation_count_warning_threshold`. Engine code installs a handler that
/// dumps all live strings to disk.
on_allocation_count_warning: ?*const fn () void = null,
pub fn create(backingAllocator: std.mem.Allocator, io_context: std.Io) !*@This() {
const self = try backingAllocator.create(@This());
self.* = .{
.backingAllocator = backingAllocator,
.io_context = io_context,
.arena = std.heap.ArenaAllocator.init(backingAllocator),
};
// default bucket setup
// zig fmt: off
try self.buckets.appendSlice(backingAllocator, &.{
Bucket.init( 0x0, 16, 4096 * 1, io_context),
Bucket.init( 0x1, 32, 4096 * 1, io_context),
Bucket.init( 0x2, 64, 4096 * 1, io_context),
Bucket.init( 0x3, 128, 4096 * 1, io_context),
Bucket.init( 0x4, 512, 4096 * 16, io_context),
Bucket.init( 0x5, 4096, 4096 * 16, io_context),
});
// zig fmt: on
return self;
}
pub fn io(self: *const @This()) std.Io {
return self.io_context;
}
pub fn getAllocator(self: *@This()) std.mem.Allocator {
return self.arena.allocator();
}
pub fn newFromUtf8(self: *@This(), str: []const u8) !RefString {
const results = try self.strNew(str.len);
std.mem.copyForwards(u8, results.bytes, str);
return results.handle;
}
pub fn newFromUtf8Concat(self: *@This(), left: []const u8, right: []const u8) !RefString {
const left_len = left.len;
const new_len = left_len + right.len;
const results = try self.strNew(new_len);
std.mem.copyForwards(u8, results.bytes[0..left_len], left);
std.mem.copyForwards(u8, results.bytes[left_len..new_len], right);
return results.handle;
}
pub fn strNew(self: *@This(), length: usize) !struct {
handle: RefString,
bytes: []u8,
} {
const bucket = self.getBucketByLen(@intCast(length));
const allocation = try bucket.assignOrRecycleSlot(self.getAllocator());
const strAllocation = StringAllocation.fromPtr(allocation.bytes.ptr);
strAllocation.initRc();
strAllocation.setLen(length);
const live = self.live_count.fetchAdd(1, .monotonic) + 1;
if (live >= self.allocation_count_warning_threshold and
!self.warning_fired.swap(true, .acq_rel))
{
std.log.warn("string-pool: live allocation count reached {d} (threshold {d})", .{
live, self.allocation_count_warning_threshold,
});
if (self.on_allocation_count_warning) |callback| callback();
}
// read current generation (may have been bumped by prior free+recycle)
const gen = strAllocation.generation();
return .{
.handle = .{
.bucketId = @intCast(bucket.id),
.index = allocation.index,
.generation = gen,
},
.bytes = strAllocation.bytes(),
};
}
inline fn getBucketByLen(self: *@This(), stringLength: u32) *Bucket {
const actualLength = stringLength + StringAllocation.HeaderLen;
for (self.buckets.items) |*bucket| {
if (bucket.allocSize >= actualLength) {
return bucket;
}
}
@panic("Unable to find a bucket to allocate string of length.");
}
inline fn getBucketFromHandle(self: @This(), handle: RefString) *Bucket {
return &self.buckets.items[@intCast(handle.bucketId)];
}
pub fn getUtf8(self: @This(), handle: RefString) []u8 {
const alloc = self.handleToAllocation(handle);
self.checkGeneration(handle, alloc);
return alloc.bytes();
}
pub fn handleLen(self: @This(), handle: RefString) usize {
const alloc = self.handleToAllocation(handle);
self.checkGeneration(handle, alloc);
return alloc.len();
}
pub fn rcAdd(self: *@This(), handle: RefString) void {
const allocation = self.handleToAllocation(handle);
self.checkGeneration(handle, allocation);
allocation.rcAdd();
}
pub fn handleToAllocation(self: @This(), handle: RefString) StringAllocation {
const bucket = self.getBucketFromHandle(handle);
return StringAllocation.fromPtr(bucket.getBytesFromIndex(handle.index).ptr);
}
fn checkGeneration(self: @This(), handle: RefString, alloc: StringAllocation) void {
_ = self;
const slotGen = alloc.generation();
if (slotGen != handle.generation) {
@panic("use-after-free: stale String handle");
}
}
pub fn strDestroy(self: *@This(), handle: RefString) void {
const allocation = self.handleToAllocation(handle);
self.checkGeneration(handle, allocation);
if (allocation.rcSub()) {
_ = self.live_count.fetchSub(1, .monotonic);
const bucket = self.getBucketFromHandle(handle);
bucket.destroySlot(self.getAllocator(), @intCast(handle.index));
}
}
/// Dumps every live string in the pool, one per line.
/// Diagnostic aid for tracking down leaks / unexpected growth.
/// Not synchronized against concurrent alloc/free; call from a quiescent
/// context or accept a racy snapshot.
pub fn dumpStrings(self: *@This(), writer: *std.Io.Writer) !void {
const allocator = self.backingAllocator;
try writer.print("string-pool dump: live_count={d}\n", .{self.live_count.load(.monotonic)});
var total: usize = 0;
for (self.buckets.items) |*bucket| {
var free_set: std.AutoHashMapUnmanaged(u32, void) = .empty;
defer free_set.deinit(allocator);
try free_set.ensureUnusedCapacity(allocator, @intCast(bucket.freeSlots.items.len));
for (bucket.freeSlots.items) |index| free_set.putAssumeCapacity(index, {});
var index: u32 = 0;
while (index < bucket.next) : (index += 1) {
if (free_set.contains(index)) continue;
const alloc = StringAllocation.fromPtr(bucket.getBytesFromIndex(index).ptr);
try writer.print("bucket={d} index={d} gen={d} rc={d} len={d} \"{s}\"\n", .{
bucket.id,
index,
alloc.generation(),
alloc.rc(),
alloc.len(),
alloc.bytes(),
});
total += 1;
}
}
try writer.print("total_live={d}\n", .{total});
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
var reserved: usize = 0;
var used: usize = 0;
for (self.buckets.items) |*bucket| {
reserved += bucket.pages.items.len * @as(usize, bucket.pageSize);
reserved += bucket.pages.capacity * @sizeOf(usize);
reserved += bucket.freeSlots.capacity * @sizeOf(u32);
used += (bucket.next - bucket.freeSlots.items.len) * @as(usize, bucket.allocSize);
}
return .{
.statName = "StringContext",
.instanceCount = self.live_count.load(.monotonic),
.memoryReserved = reserved,
.memoryUsed = used,
};
}
pub fn destroy(self: *@This()) void {
self.arena.deinit();
self.buckets.deinit(self.backingAllocator);
self.backingAllocator.destroy(self);
}
};
pub fn setup(allocator: std.mem.Allocator, io_context: std.Io) !void {
gStringContext = try StringContext.create(allocator, io_context);
}
pub fn shutdown() void {
gStringContext.destroy();
}
/// Dumps all live strings in the global pool to `writer`.
pub fn dumpStrings(writer: *std.Io.Writer) !void {
try gStringContext.dumpStrings(writer);
}
test "string context" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const ctx = gStringContext;
const testSizes: []const u32 = &.{ 14, 15, 16, 12, 32, 10, 1, 2, 3, 4, 440, 450, 3200 };
for (testSizes) |testSize| {
const results = try ctx.strNew(testSize);
std.debug.print("test {d} = {d}, {d}\n", .{ testSize, results.handle.bucketId, results.handle.index });
}
const L = struct {
pub fn wrap(x: RefString) void {
std.debug.print("{d},{d}\n", .{ x.bucketId, x.index });
}
};
const s = try RefString.new("lmao2nova");
L.wrap(s);
const x = s.utf8();
std.debug.print("{x}\n", .{x.len});
// doing 1Billion accesses
{
const now = std.Io.Clock.awake.now(ctx.io()).nanoseconds;
for (0..1_000_000_000) |i| {
_ = i;
_ = s.utf8();
}
const end = std.Io.Clock.awake.now(ctx.io()).nanoseconds;
const duration = end - now;
std.debug.print("time spent {d}ms\n", .{@as(f64, @floatFromInt(duration)) / 1000_000});
}
{
const now = std.Io.Clock.awake.now(ctx.io()).nanoseconds;
// 1 million string creations/destructions
for (0..1_000_000) |i| {
_ = i;
const y = try RefString.new("wutang forever\n");
defer y.drop();
}
const end = std.Io.Clock.awake.now(ctx.io()).nanoseconds;
const duration = end - now;
std.debug.print("time spent {d}ms\n", .{@as(f64, @floatFromInt(duration)) / 1000_000});
}
// allocate 1 million strings
const s2 = s.pin();
defer s2.drop();
}
test "len" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new("hello");
defer s.drop();
try std.testing.expectEqual(@as(usize, 5), s.len());
}
test "append" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new("hello");
// append drops the old handle, returns new
const s2 = try s.append(" world");
defer s2.drop();
try std.testing.expectEqualStrings("hello world", s2.getUtf8());
}
test "concat keeps operands alive" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const left = try RefString.new("hello");
defer left.drop();
const right = try RefString.new(" world");
defer right.drop();
const joined = try left.concat(right);
defer joined.drop();
try std.testing.expectEqualStrings("hello world", joined.getUtf8());
try std.testing.expectEqualStrings("hello", left.getUtf8());
try std.testing.expectEqualStrings(" world", right.getUtf8());
}
test "concatSlice" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const left = try RefString.new("rib");
defer left.drop();
const joined = try left.concatSlice("tech");
defer joined.drop();
try std.testing.expectEqualStrings("ribtech", joined.getUtf8());
try std.testing.expectEqualStrings("rib", left.getUtf8());
}
test "trim with whitespace" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new(" hello ");
defer s.drop();
const trimmed = try s.trim();
defer trimmed.drop();
try std.testing.expectEqualStrings("hello", trimmed.getUtf8());
}
test "trim without whitespace" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new("abc");
defer s.drop();
const trimmed = try s.trim();
defer trimmed.drop();
try std.testing.expectEqualStrings("abc", trimmed.getUtf8());
// pinned copy — same handle
try std.testing.expectEqual(s.index, trimmed.index);
try std.testing.expectEqual(s.bucketId, trimmed.bucketId);
}
test "substring" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new("hello world");
defer s.drop();
const sub = try s.substring(6, 11);
defer sub.drop();
try std.testing.expectEqualStrings("world", sub.getUtf8());
// clamping
const sub2 = try s.substring(6, 999);
defer sub2.drop();
try std.testing.expectEqualStrings("world", sub2.getUtf8());
// substringSlice
try std.testing.expectEqualStrings("world", s.substringSlice(6, 11));
}
test "split" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.new("a::b::c");
defer s.drop();
const result = try s.split("::");
defer result.deinit();
try std.testing.expectEqual(@as(usize, 3), result.items.len);
try std.testing.expectEqualStrings("a", result.items[0].getUtf8());
try std.testing.expectEqualStrings("b", result.items[1].getUtf8());
try std.testing.expectEqualStrings("c", result.items[2].getUtf8());
}
test "fmt" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s = try RefString.fmt("hello {s} {d}", .{ "world", 42 });
defer s.drop();
try std.testing.expectEqualStrings("hello world 42", s.getUtf8());
}
test "eql and eqlSlice" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const s1 = try RefString.new("hello");
defer s1.drop();
const s2 = try RefString.new("hello");
defer s2.drop();
const s3 = try RefString.new("world");
defer s3.drop();
try std.testing.expect(s1.eql(s2));
try std.testing.expect(!s1.eql(s3));
// pinned handle — fast path
const s4 = s1.pin();
defer s4.drop();
try std.testing.expect(s1.eql(s4));
try std.testing.expect(s1.eqlSlice("hello"));
try std.testing.expect(!s1.eqlSlice("world"));
}
test "multithread create and destroy" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const ThreadCtx = struct {
threadId: usize,
iterations: usize,
};
const Worker = struct {
fn run(ctx: ThreadCtx) void {
var i: usize = 0;
while (i < ctx.iterations) : (i += 1) {
var s = RefString.fmt("t{d}-i{d}", .{ ctx.threadId, i }) catch unreachable;
if (@mod(i, 5) == 0) {
const s2 = s.append("-x") catch unreachable;
s = s2;
}
if (@mod(i, 7) == 0) {
const p = s.pin();
p.drop();
}
s.drop();
}
}
};
const threadCount: usize = 8;
const iterationsPerThread: usize = 3000;
var threads: [threadCount]std.Thread = undefined;
for (0..threadCount) |tid| {
threads[tid] = try std.Thread.spawn(.{}, Worker.run, .{ThreadCtx{
.threadId = tid,
.iterations = iterationsPerThread,
}});
}
for (threads) |t| t.join();
const s = try RefString.new("post-thread-sanity");
defer s.drop();
try std.testing.expectEqualStrings("post-thread-sanity", s.getUtf8());
}
test "multithread shared pin and drop" {
try setup(std.testing.allocator, std.testing.io);
defer shutdown();
const base = try RefString.new("shared-handle");
defer base.drop();
const ThreadCtx = struct {
handle: RefString,
iterations: usize,
};
const Worker = struct {
fn run(ctx: ThreadCtx) void {
var i: usize = 0;
while (i < ctx.iterations) : (i += 1) {
const p = ctx.handle.pin();
if (@mod(i, 16) == 0) {
_ = p.len();
}
p.drop();
}
}
};
const threadCount: usize = 12;
const iterationsPerThread: usize = 6000;
var threads: [threadCount]std.Thread = undefined;
for (0..threadCount) |tid| {
threads[tid] = try std.Thread.spawn(.{}, Worker.run, .{ThreadCtx{
.handle = base,
.iterations = iterationsPerThread,
}});
}
for (threads) |t| t.join();
try std.testing.expectEqualStrings("shared-handle", base.getUtf8());
}

View File

@ -0,0 +1,164 @@
// experiment with a specialized logging infrastructure.
// structured logging.
//
// It can log to an ultra tiny in-memory buffer directly,
// or it can log to a second writer thread.
// but the way it all works is it goes through this logger
const BumpArena = @import("bump-arena.zig");
pub const Verbosity = enum(u8) {
verbose,
log,
warn,
err,
};
var gLoggerContext: LoggerContext = undefined;
pub const LoggerContext = struct {
stdout_buffer: [8192 * 8]u8 = undefined,
stdout_file_writer: std.Io.File.Writer = undefined,
stdout_writer: *std.Io.Writer = undefined,
arena: std.heap.ArenaAllocator = undefined,
backing: std.mem.Allocator = undefined,
logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty,
logMapById: std.ArrayList(LogRef) = .empty,
loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty,
loggerStatesById: std.ArrayList(*LoggerState) = .empty,
pub fn insertLoggerStateOrGetId(self: *@This(), state: *LoggerState) u32 {
if (state.id > -1) {
return @intCast(state.id);
}
if (self.loggerStates.get(state)) |id| {
return id;
}
const allocator = self.arena.allocator();
const rv: u32 = @intCast(self.loggerStatesById.items.len);
self.loggerStates.put(allocator, state, rv) catch @panic("unbounded arena oom");
self.loggerStatesById.append(allocator, state) catch @panic("unbounded arena saw oom");
return rv;
}
pub fn insertLogRefOrGetId(self: *@This(), ref: LogRef, idref: *i32) u32 {
if (idref.* > -1) {
return @intCast(idref.*);
}
if (self.logMap.get(ref)) |key| {
idref.* = @intCast(key);
return key;
}
const allocator = self.arena.allocator();
const rv: u32 = @intCast(self.logMapById.items.len);
self.logMapById.append(allocator, ref) catch @panic("unbounded arena saw oom");
self.logMap.put(allocator, ref, rv) catch @panic("unbounded arena saw oom");
idref.* = @intCast(rv);
return rv;
}
pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void {
self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer);
self.stdout_writer = &self.stdout_file_writer.interface;
self.backing = allocator;
self.arena = std.heap.ArenaAllocator.init(self.backing);
}
pub fn deinit(self: *@This()) void {
self.arena.deinit();
}
};
pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void {
gLoggerContext.init(io, allocator);
}
pub fn deinit() void {
gLoggerContext.deinit();
}
pub fn flush() void {
gLoggerContext.stdout_writer.flush() catch {};
}
pub const LogRef = struct {
line: u32,
file: []const u8,
fmt: []const u8,
pub const Context = struct {
pub fn hash(_: @This(), key: LogRef) u64 {
var hasher = std.hash.Wyhash.init(0);
hasher.update(key.file);
hasher.update(std.mem.asBytes(&key.line));
hasher.update(std.mem.asBytes(&key.fmt));
return hasher.final();
}
pub fn eql(_: @This(), a: LogRef, b: LogRef) bool {
return a.line == b.line and std.mem.eql(u8, a.file, b.file);
}
};
pub fn fromSrcFmt(comptime s: std.builtin.SourceLocation, comptime fmt: []const u8) @This() {
return .{
.line = s.line,
.file = @ptrCast(s.file),
.fmt = fmt,
};
}
};
pub const LoggerState = struct { name: []const u8, verbosity: Verbosity, id: i32 = -1 };
pub fn DeclareLogger(comptime LoggerName: []const u8, defaultVerbosity: Verbosity) type {
return struct {
pub var loggerState: LoggerState = .{
.name = LoggerName,
.verbosity = defaultVerbosity,
};
const debug = true;
pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void {
const FmtState = struct {
pub const FMT = fmt;
pub var index: i32 = -1;
};
// create a hash of the s: builtin sourcelocation
const sourceId = gLoggerContext.insertLogRefOrGetId(LogRef.fromSrcFmt(s, fmt), &FmtState.index);
const loggerId = gLoggerContext.insertLoggerStateOrGetId(&loggerState);
if (@intFromEnum(loggerState.verbosity) > @intFromEnum(v)) {
return;
}
if (debug) {
gLoggerContext.stdout_writer.print("[{d}] [{d}] ", .{ loggerId, sourceId }) catch @panic("io error");
gLoggerContext.stdout_writer.print(fmt ++ "\n", args) catch @panic("io error");
}
}
};
}
const std = @import("std");
const builtin = @import("builtin");
test "init logger" {
initialize(std.testing.io, std.testing.allocator);
defer deinit();
const TestLogger = DeclareLogger("Testing", .log);
TestLogger.addLog(@src(), .log, "testing", .{});
flush();
}

View File

@ -0,0 +1,226 @@
const std = @import("std");
pub fn createFileWithPath(io: std.Io, filePath: []const u8) !std.Io.File {
var splitEndIterator = std.mem.splitBackwardsAny(u8, filePath, "\\/");
if (splitEndIterator.next()) |first| {
const newSlice = filePath[0 .. filePath.len - first.len];
std.debug.print("ensuring Dir is created {s}\n", .{newSlice});
try std.Io.Dir.cwd().createDirPath(io, newSlice);
}
return std.Io.Dir.cwd().createFile(io, filePath, .{ .read = true, .truncate = true });
}
pub fn makePathAny(io: std.Io, path: []const u8) !void {
if (!std.Io.Dir.path.isAbsolute(path)) {
return std.Io.Dir.cwd().createDirPath(io, path);
}
std.Io.Dir.accessAbsolute(io, path, .{}) catch |err| switch (err) {
error.FileNotFound => {},
else => return err,
};
const parent = std.Io.Dir.path.dirname(path) orelse return;
if (parent.len > 0 and !std.mem.eql(u8, parent, path)) {
try makePathAny(io, parent);
}
std.Io.Dir.createDirAbsolute(io, path, .default_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => return err,
};
}
pub fn loadFileAlloc(io: std.Io, filename: []const u8, comptime alignment: std.mem.Alignment, allocator: std.mem.Allocator) ![]u8 {
const cwd = std.Io.Dir.cwd();
const filesize = (try cwd.statFile(io, filename, .{})).size + 1; // add null byte
const buffer: []u8 = try allocator.alignedAlloc(u8, alignment, filesize);
errdefer allocator.free(buffer);
var file = try cwd.openFile(io, filename, .{});
defer file.close(io);
var read_buffer: [4096]u8 = undefined;
var reader = file.reader(io, &read_buffer);
try reader.interface.readSliceAll(buffer[0 .. buffer.len - 1]);
buffer[buffer.len - 1] = 0;
return buffer;
}
pub fn grapvizDotToPng(allocator: std.mem.Allocator, io: std.Io, vizFile: []const u8, pngFile: []const u8) !void {
const sourceFile = try std.fmt.allocPrint(allocator, "Saved/{s}", .{vizFile});
defer allocator.free(sourceFile);
const imageFile = try std.fmt.allocPrint(allocator, "Saved/{s}", .{pngFile});
defer allocator.free(imageFile);
var child = try std.process.spawn(io, .{
.argv = &.{ "dot", "-Tpng", sourceFile, "-o", imageFile },
});
_ = try child.wait(io);
}
pub fn dupeString(allocator: std.mem.Allocator, string: []const u8) ![]u8 {
const dupe = try allocator.alloc(u8, string.len);
std.mem.copyForwards(u8, dupe, string);
return dupe;
}
pub const FileLog = struct {
buffer: std.Io.Writer.Allocating,
allocator: std.mem.Allocator,
fileName: []u8,
pub fn init(allocator: std.mem.Allocator, fileName: []const u8) !@This() {
return .{
.buffer = std.Io.Writer.Allocating.init(allocator),
.allocator = allocator,
.fileName = try dupeString(allocator, fileName),
};
}
pub fn write(self: *@This(), comptime fmt: []const u8, args: anytype) !void {
try self.buffer.writer.print(fmt, args);
}
pub fn writeOut(self: @This(), io: std.Io) !void {
const cwd = std.Io.Dir.cwd();
const ofile = try std.fmt.allocPrint(self.allocator, "Saved/{s}", .{self.fileName});
defer self.allocator.free(ofile);
try cwd.createDirPath(io, "Saved");
try cwd.writeFile(io, .{ .sub_path = ofile, .data = self.buffer.written() });
}
pub fn deinit(self: *@This()) void {
self.allocator.free(self.fileName);
self.buffer.deinit();
}
};
pub fn assertf(eval: anytype, comptime fmt: []const u8, args: anytype) !void {
if (!eval) {
std.debug.print("\n\n[Error]: " ++ fmt ++ "\n\n", args);
return error.AssertFailure;
}
}
pub fn asserts(eval: anytype, comptime fmt: []const u8, args: anytype, comptime tag: []const u8) void {
if (!eval) {
std.debug.print("[Error]: " ++ fmt, args);
std.debug.print("> " ++ tag, .{});
@panic("assertion failed");
}
}
pub fn assert(eval: anytype) !void {
if (!eval) {
return error.AssertFailure;
}
}
// gets the basename of the file/path
pub fn getBasePath(path: []const u8) []const u8 {
if (path.len == 0) {
return "";
}
if (path[path.len - 1] == '/' or path[path.len - 1] == '\\') {
return getBasePath(path[0 .. path.len - 1]);
}
var i: i32 = @intCast(path.len - 1);
while (i >= 0) : (i -= 1) {
const c = path[@intCast(i)];
if (c == '/' or c == '\\') {
return path[@intCast(i + 1)..];
}
}
return path;
}
// gets the folder name of the dir/path
pub fn getFolder(path: []const u8) []const u8 {
if (path.len == 0) {
unreachable;
}
if (path[path.len - 1] == '/' or path[path.len - 1] == '\\') {
return getBasePath(path[0 .. path.len - 1]);
}
var i: i32 = @intCast(path.len - 1);
while (i >= 0) : (i -= 1) {
const c = path[@intCast(i)];
if (c == '/' or c == '\\') {
return path[0..@intCast(i)];
}
}
return path;
}
pub fn getFileExtension(path: []const u8) []const u8 {
for (path, 0..) |c, i| {
if (c == '.') {
return path[i..];
}
}
return path;
}
// removes whitespace from start and end
pub fn stringStrip(p: []const u8) []const u8 {
var s: usize = 0;
while (s < p.len) : (s += 1) {
if (!std.ascii.isWhitespace(p[s])) {
break;
}
}
var e: usize = p.len;
while (e > 0) : (e -= 1) {
if (!std.ascii.isWhitespace(p[e - 1])) {
break;
}
}
if (s >= e) return p[0..0];
return p[s..e];
}
pub fn splitSliceWork(comptime T: type, slice: []T, id: u32, count: u32) struct { slice: []T, startIndex: usize } {
const stride = @divFloor(slice.len, count);
const rem = @rem(slice.len, count);
// let s = stride if index < remainder
// let r = stride if index >= remainder
//
// formula:
// x < R; start = s * x; stride = s
// x >=R; start = R * s + (x - R) * r; stride = r
//
// combining...
//
const s = stride + 1;
const r = stride;
if (id < rem) {
const start = s * id;
return .{ .slice = slice[start .. start + s], .startIndex = start };
} else {
const start = s * rem + (id - rem) * r;
return .{ .slice = slice[start .. start + r], .startIndex = start };
}
}
test "stringStrip handles empty and whitespace-only input" {
try std.testing.expectEqualStrings("", stringStrip(""));
try std.testing.expectEqualStrings("", stringStrip(" \t\r\n"));
try std.testing.expectEqualStrings("abc", stringStrip(" \t abc \n"));
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,117 @@
const std = @import("std");
const p2 = @import("../p2.zig");
pub const ShellProcess = struct {
backingAllocator: std.mem.Allocator,
argv: []const []const u8 = undefined,
ownedArgs: ?[][]u8 = null,
stringArena: p2.BumpArena = undefined,
// initialize the shellprocess from a windows cmd string
pub fn initCmd(alloc: std.mem.Allocator, io: std.Io, cmd: []const u8) !*@This() {
const self = try alloc.create(@This());
self.* = .{
.backingAllocator = alloc,
.stringArena = try p2.BumpArena.init(alloc, io),
};
try self.splitArgsFromCmd(cmd);
return self;
}
pub fn init(alloc: std.mem.Allocator, io: std.Io, argv: []const []const u8) !*@This() {
const self = try alloc.create(@This());
self.* = .{
.backingAllocator = alloc,
.stringArena = try p2.BumpArena.init(alloc, io),
};
try self.setArgsOwned(argv);
return self;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return self.stringArena.allocator();
}
pub fn splitArgsFromCmd(self: *@This(), cmd: []const u8) !void {
var currentCmd = std.ArrayList(u8).empty;
var ownedArgs = std.ArrayList([]u8).empty;
var terminalStack = std.ArrayList(u8).empty;
defer terminalStack.deinit(self.backingAllocator);
for (cmd) |c| {
if (terminalStack.items.len == 0) {
if (c == ' ') {
try ownedArgs.append(self.allocator(), try currentCmd.toOwnedSlice(self.allocator()));
} else if (c == '\'' or c == '\"') {
try terminalStack.append(self.backingAllocator, c);
try currentCmd.append(self.allocator(), c);
} else {
try currentCmd.append(self.allocator(), c);
}
} else {
if (terminalStack.items[terminalStack.items.len - 1] == c) {
try currentCmd.append(self.allocator(), terminalStack.pop().?);
} else {
try currentCmd.append(self.allocator(), c);
}
}
}
try ownedArgs.append(self.allocator(), try currentCmd.toOwnedSlice(self.allocator()));
self.ownedArgs = try ownedArgs.toOwnedSlice(self.allocator());
self.argv = @ptrCast(self.ownedArgs.?);
}
pub fn setArgsOwned(self: *@This(), args: []const []const u8) !void {
self.ownedArgs = try self.allocator().alloc([]u8, args.len);
for (args, 0..) |s, i| {
self.ownedArgs.?[i] = try self.allocator().dupe(u8, s);
}
self.argv = @ptrCast(self.ownedArgs.?);
}
pub fn deinit(self: *@This()) void {
self.stringArena.deinit();
self.backingAllocator.destroy(self);
}
};
// TODO this is really bad
pub fn runCmd(allocator: std.mem.Allocator, io: std.Io, cmd: []const []const u8, cwd: []const u8) ![]u8 {
const result = try std.process.run(allocator, io, .{
.argv = cmd,
.cwd = .{ .path = p2.getFolder(cwd) },
.stdout_limit = .limited(150 * 1024 * 1024),
.stderr_limit = .limited(150 * 1024 * 1024),
});
defer allocator.free(result.stderr);
switch (result.term) {
.exited => |code| {
if (code == 0) {
std.debug.print("runCmd stdout: {s}\n", .{result.stdout});
return result.stdout;
} else {
defer allocator.free(result.stdout);
std.debug.print("runCmd stdout: {s}\n", .{result.stdout});
std.debug.print("stderr: {s}\n", .{result.stderr});
return error.NonZeroExitCode;
}
},
else => {
allocator.free(result.stdout);
return error.Terminated;
},
}
return result.stdout;
}

102
engine/p2/src/utils/xxd.zig Normal file
View File

@ -0,0 +1,102 @@
const std = @import("std");
const Endian = enum {
big,
little,
};
pub const XxdOptions = struct {
wordSize: u32 = 8, // in bits
endian: Endian = .little,
wordsPerGroup: u32 = 2, // in number of words
groupsPerLine: u32 = 8, // number of bytes per word
groupSplit: u32 = 4, // insert a double space every x number of
showAddress: bool = true,
};
pub fn xxdWrite(
writer: anytype,
bytes: []const u8,
options: XxdOptions,
) !void {
var wordBuffer: [16]u8 = undefined;
var wordOffset: usize = 0;
const bytesPerWord = options.wordSize / 8;
var wordInGroup: usize = 0;
var groupInLine: usize = 0;
for (bytes, 0..) |byte, index| {
if (wordInGroup == options.wordsPerGroup) {
if ((groupInLine + 1) % options.groupSplit == 0 and wordInGroup == options.wordsPerGroup) {
try writer.writeByte(' ');
}
try writer.writeByte(' ');
wordInGroup = 0;
groupInLine += 1;
if (groupInLine == options.groupsPerLine) {
try writer.writeByte('\n');
groupInLine = 0;
}
}
if (options.showAddress) {
if (wordInGroup == 0 and wordOffset == 0 and groupInLine == 0) {
try writer.print("{x:6.0}: ", .{index});
}
}
wordBuffer[wordOffset] = byte;
wordOffset += 1;
if (wordOffset == bytesPerWord) {
// write out the word into the reader according to endian
var wordOffsetIndex: usize = 0;
while (wordOffsetIndex < bytesPerWord) : (wordOffsetIndex += 1) {
const wordByte = if (options.endian == .little)
wordBuffer[wordOffsetIndex]
else
wordBuffer[bytesPerWord - 1 - wordOffsetIndex];
try writeByteAsHex(wordByte, writer);
}
wordOffset = 0;
}
wordInGroup += 1;
}
_ = try writer.write(".\n");
}
inline fn writeByteAsHex(byte: u8, writer: anytype) !void {
const hex = byteAsHex(byte);
try writer.writeByte(hex[1]);
try writer.writeByte(hex[0]);
}
inline fn byteAsHex(byte: u8) [2]u8 {
var rv: [2]u8 = undefined;
rv[1] = nibbleAsHex(byte >> 4);
rv[0] = nibbleAsHex(byte & 0xF);
return rv;
}
fn nibbleAsHex(nib: u8) u8 {
if (nib < 10)
return '0' + nib;
return 'A' - 10 + nib;
}
test "testing all" {
std.debug.print("\n", .{});
const writer = std.io.getStdOut().writer();
try writeByteAsHex(0x2f, writer);
std.debug.print("\n\n", .{});
try xxdWrite(writer, &[_]u8{ 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22 }, .{});
std.debug.print("\n", .{});
}

View File

@ -0,0 +1,59 @@
# P2 VS Code Environment
This directory holds the repo-local definition for a pinned/custom VS Code setup.
It is meant to live under `lib/p2`, while installing generated launcher files at
the workspace root.
## Layout
- `extensions/`: put vendored `.vsix` files here.
- `settings/settings.json`: settings copied into the isolated VS Code user data.
- `install.sh`: installs the environment into the workspace root.
## Install
From `lib/p2`:
```sh
./tools/vscode-env/install.sh
```
By default this creates:
- `<workspace-root>/.vscode-p2/`
- `<workspace-root>/.bin/p2-code`
- `<workspace-root>/.bin/p2-code.bat`
- `<workspace-root>/p2.code-workspace`
Run the environment with:
```sh
<workspace-root>/.bin/p2-code
```
The wrapper uses an isolated `--user-data-dir` and `--extensions-dir`, so custom
extensions do not affect your normal VS Code profile.
On Windows, run:
```bat
<workspace-root>\.bin\p2-code.bat
```
## Vendored Extensions
Drop custom or forked extensions into `extensions/` as `.vsix` files, then rerun
`install.sh`. The installer will install every `.vsix` it finds into the isolated
extension directory.
For example:
```sh
cp ~/dev/vscode-zig/ziglang.vscode-zig-0.6.18-custom.vsix tools/vscode-env/extensions/
./tools/vscode-env/install.sh
```
Custom language extensions can live next to the tool they support, such as
`tools/riblang/vscode/`, and publish a packaged `.vsix` into this directory.
That keeps the source near the language implementation while keeping the editor
environment installer simple and pinned.

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,137 @@
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SCRIPT_DIR=%~dp0"
if "%SCRIPT_DIR:~-1%"=="\" set "SCRIPT_DIR=%SCRIPT_DIR:~0,-1%"
for %%I in ("%SCRIPT_DIR%\..\..") do set "P2_DIR=%%~fI"
set "WORKSPACE_ROOT="
set "CODE_BIN=code"
:parse_args
if "%~1"=="" goto after_args
if /I "%~1"=="--workspace-root" (
if "%~2"=="" (
echo missing value for --workspace-root 1>&2
exit /b 2
)
set "WORKSPACE_ROOT=%~2"
shift
shift
goto parse_args
)
if /I "%~1"=="--code-bin" (
if "%~2"=="" (
echo missing value for --code-bin 1>&2
exit /b 2
)
set "CODE_BIN=%~2"
shift
shift
goto parse_args
)
if /I "%~1"=="-h" goto usage
if /I "%~1"=="--help" goto usage
echo unknown argument: %~1 1>&2
goto usage_error
:after_args
if "%WORKSPACE_ROOT%"=="" (
for /f "usebackq delims=" %%I in (`git -C "%P2_DIR%" rev-parse --show-toplevel 2^>nul`) do set "WORKSPACE_ROOT=%%I"
)
if "%WORKSPACE_ROOT%"=="" set "WORKSPACE_ROOT=%P2_DIR%"
for %%I in ("%WORKSPACE_ROOT%") do set "WORKSPACE_ROOT=%%~fI"
set "ENV_DIR=%WORKSPACE_ROOT%\.vscode-p2"
set "BIN_DIR=%WORKSPACE_ROOT%\.bin"
set "USER_DATA_DIR=%ENV_DIR%\user-data"
set "EXTENSIONS_DIR=%ENV_DIR%\extensions"
set "WORKSPACE_FILE=%WORKSPACE_ROOT%\p2.code-workspace"
mkdir "%BIN_DIR%" 2>nul
mkdir "%USER_DATA_DIR%\User" 2>nul
mkdir "%EXTENSIONS_DIR%" 2>nul
copy /Y "%SCRIPT_DIR%\settings\settings.json" "%USER_DATA_DIR%\User\settings.json" >nul
(
echo @echo off
echo setlocal
echo.
echo if "%%CODE_BIN%%"=="" ^(
echo set "CODE_BIN=%CODE_BIN%"
echo ^)
echo.
echo set "WORKSPACE_ROOT=%WORKSPACE_ROOT%"
echo set "ENV_DIR=%%WORKSPACE_ROOT%%\.vscode-p2"
echo.
echo "%%CODE_BIN%%" ^^
echo --user-data-dir "%%ENV_DIR%%\user-data" ^^
echo --extensions-dir "%%ENV_DIR%%\extensions" ^^
echo "%%WORKSPACE_ROOT%%\p2.code-workspace" ^^
echo %%*
) > "%BIN_DIR%\p2-code.bat"
set "P2_REL=%P2_DIR%"
set "P2_REL=!P2_REL:%WORKSPACE_ROOT%=!"
if "!P2_REL:~0,1!"=="\" set "P2_REL=!P2_REL:~1!"
set "P2_REL=!P2_REL:\=/!"
(
echo {
echo "folders": [
echo {
echo "name": "snow",
echo "path": "."
echo },
echo {
echo "name": "p2",
echo "path": "!P2_REL!"
echo }
echo ],
echo "settings": {
echo "editor.foldingStrategy": "auto"
echo }
echo }
) > "%WORKSPACE_FILE%"
where "%CODE_BIN%" >nul 2>nul
if errorlevel 1 (
echo VS Code binary not found: %CODE_BIN% 1>&2
echo Skipping .vsix installation. Re-run with --code-bin PATH when available. 1>&2
) else (
set "FOUND_VSIX=0"
for %%F in ("%SCRIPT_DIR%\extensions\*.vsix") do (
if exist "%%~fF" (
set "FOUND_VSIX=1"
"%CODE_BIN%" --extensions-dir "%EXTENSIONS_DIR%" --install-extension "%%~fF"
)
)
if "!FOUND_VSIX!"=="0" echo No vendored .vsix files found in %SCRIPT_DIR%\extensions
)
echo Installed P2 VS Code environment:
echo windows: %BIN_DIR%\p2-code.bat
echo workspace: %WORKSPACE_FILE%
echo user data: %USER_DATA_DIR%
echo extensions:%EXTENSIONS_DIR%
echo.
echo Run:
echo %BIN_DIR%\p2-code.bat
exit /b 0
:usage
echo Usage: install.bat [--workspace-root PATH] [--code-bin CODE]
echo.
echo Installs the P2 VS Code environment at the workspace root.
echo.
echo Options:
echo --workspace-root PATH Override the detected Git root.
echo --code-bin CODE VS Code binary to use for installing .vsix files.
echo -h, --help Show this help.
exit /b 0
:usage_error
call :usage
exit /b 2

View File

@ -0,0 +1,145 @@
#!/usr/bin/env sh
set -eu
usage() {
cat <<'EOF'
Usage: install.sh [--workspace-root PATH] [--code-bin CODE]
Installs the P2 VS Code environment at the workspace root.
Options:
--workspace-root PATH Override the detected Git root.
--code-bin CODE VS Code binary to use for installing .vsix files.
-h, --help Show this help.
EOF
}
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
p2_dir=$(CDPATH= cd -- "$script_dir/../.." && pwd)
workspace_root=
code_bin=${CODE_BIN:-code}
while [ "$#" -gt 0 ]; do
case "$1" in
--workspace-root)
[ "$#" -ge 2 ] || {
echo "missing value for --workspace-root" >&2
exit 2
}
workspace_root=$2
shift 2
;;
--code-bin)
[ "$#" -ge 2 ] || {
echo "missing value for --code-bin" >&2
exit 2
}
code_bin=$2
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "unknown argument: $1" >&2
usage >&2
exit 2
;;
esac
done
if [ -z "$workspace_root" ]; then
workspace_root=$(git -C "$p2_dir" rev-parse --show-toplevel 2>/dev/null || printf '%s\n' "$p2_dir")
fi
workspace_root=$(CDPATH= cd -- "$workspace_root" && pwd)
env_dir="$workspace_root/.vscode-p2"
bin_dir="$workspace_root/.bin"
user_data_dir="$env_dir/user-data"
extensions_dir="$env_dir/extensions"
workspace_file="$workspace_root/p2.code-workspace"
mkdir -p "$bin_dir" "$user_data_dir/User" "$extensions_dir"
cp "$script_dir/settings/settings.json" "$user_data_dir/User/settings.json"
cat > "$bin_dir/p2-code" <<EOF
#!/usr/bin/env sh
set -eu
code_bin=\${CODE_BIN:-$code_bin}
workspace_root=$workspace_root
env_dir=\$workspace_root/.vscode-p2
exec "\$code_bin" \\
--user-data-dir "\$env_dir/user-data" \\
--extensions-dir "\$env_dir/extensions" \\
"\$workspace_root/p2.code-workspace" \\
"\$@"
EOF
chmod +x "$bin_dir/p2-code"
cat > "$bin_dir/p2-code.bat" <<EOF
@echo off
setlocal
if "%CODE_BIN%"=="" (
set "CODE_BIN=$code_bin"
) else (
set "CODE_BIN=%CODE_BIN%"
)
set "WORKSPACE_ROOT=$workspace_root"
set "ENV_DIR=%WORKSPACE_ROOT%\\.vscode-p2"
"%CODE_BIN%" ^
--user-data-dir "%ENV_DIR%\\user-data" ^
--extensions-dir "%ENV_DIR%\\extensions" ^
"%WORKSPACE_ROOT%\\p2.code-workspace" ^
%*
EOF
cat > "$workspace_file" <<EOF
{
"folders": [
{
"name": "snow",
"path": "."
},
{
"name": "p2",
"path": "$(realpath --relative-to "$workspace_root" "$p2_dir")"
}
],
"settings": {
"editor.foldingStrategy": "auto"
}
}
EOF
if command -v "$code_bin" >/dev/null 2>&1; then
found_vsix=false
for vsix in "$script_dir"/extensions/*.vsix; do
[ -e "$vsix" ] || continue
found_vsix=true
"$code_bin" --extensions-dir "$extensions_dir" --install-extension "$vsix"
done
if [ "$found_vsix" = false ]; then
echo "No vendored .vsix files found in $script_dir/extensions"
fi
else
echo "VS Code binary not found: $code_bin" >&2
echo "Skipping .vsix installation. Re-run with --code-bin PATH when available." >&2
fi
cat <<EOF
Installed P2 VS Code environment:
wrapper: $bin_dir/p2-code
windows: $bin_dir/p2-code.bat
workspace: $workspace_file
user data: $user_data_dir
extensions:$extensions_dir
Run:
$bin_dir/p2-code
EOF

View File

@ -0,0 +1,7 @@
{
"editor.foldingStrategy": "auto",
"extensions.autoCheckUpdates": false,
"extensions.autoUpdate": false,
"telemetry.telemetryLevel": "off",
"zig.path": "zig"
}

View File

@ -1,4 +1,4 @@
/// desc: core crea /// desc: we will we will rock you
pub export fn core_start() callconv(.c) void {} pub export fn core_start() callconv(.c) void {}
pub export fn core_shutdown() callconv(.c) void {} pub export fn core_shutdown() callconv(.c) void {}

View File

@ -1 +1,9 @@
// this thing eats a ribtech top level // this thing eats a ribtech top level
pub fn main(init: std.process.Init) !void {
const args = init.minimal.args;
const argsSlice = try args.toSlice(init.arena.allocator());
}
const std = @import("std");