removing lots of old cruft from p2

This commit is contained in:
Peterino 2026-11-22 16:34:04 -07:00
parent 96ae04cb4b
commit 743150514a
17 changed files with 32 additions and 3481 deletions

View File

@ -12,6 +12,10 @@ Heavy usage of LLMs does drastically impact your ability to understand the low l
I hope you will enjoy coming along for the journey. I hope you will enjoy coming along for the journey.
# Note on naming:
Ribtech is the temporary name it may be renamed to something else, perhaps a bit more whimsical.
# LLM Policy # LLM Policy
You may use LLMs to assist with whatever you need assistance with, but for one solid rule: You may use LLMs to assist with whatever you need assistance with, but for one solid rule:

View File

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

View File

@ -4,26 +4,16 @@ const std = @import("std");
pub const stats = @import("structures/stats.zig"); pub const stats = @import("structures/stats.zig");
pub const PoolStatistics = stats.PoolStatistics; 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 BumpArenaThreaded = @import("structures/bump-arena.zig").BumpArenaThreaded; pub const BumpArenaThreaded = @import("structures/bump-arena.zig").BumpArenaThreaded;
pub const BumpArenaAdvanced = @import("structures/bump-arena.zig").BumpArenaAdvanced; pub const BumpArenaAdvanced = @import("structures/bump-arena.zig").BumpArenaAdvanced;
pub const BumpCheckpoint = @import("structures/bump-arena.zig").BumpCheckpoint; pub const BumpCheckpoint = @import("structures/bump-arena.zig").BumpCheckpoint;
pub const pscopes = @import("structures/pscopes.zig"); pub const pscopes = @import("structures/pscopes.zig");
pub const dupeString = utils.dupeString;
pub const xxd = @import("structures/xxd.zig"); pub const xxd = @import("structures/xxd.zig");
pub const stringStrip = utils.stringStrip;
pub const xxdWrite = xxd.xxdWrite; pub const xxdWrite = xxd.xxdWrite;
pub const loadFileAlloc = utils.loadFileAlloc;
const ArrayList = std.ArrayList; const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged; const ArrayListUnmanaged = std.ArrayListUnmanaged;
pub const interface = @import("structures/interface.zig"); pub const interface = @import("structures/interface.zig");
@ -31,16 +21,6 @@ pub const MakeInterface = interface.MakeInterface;
pub const Reference = interface.Reference; pub const Reference = interface.Reference;
pub const refFromPtr = interface.refFromPtr; 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 math = @import("structures/math.zig");
pub const zm = math.zm; pub const zm = math.zm;
@ -49,54 +29,20 @@ pub const ring_queue = @import("structures/ring-queue.zig");
pub const RingQueueU = ring_queue.RingQueueU; pub const RingQueueU = ring_queue.RingQueueU;
pub const RingQueue = ring_queue.RingQueue; 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 stack_structures = @import("structures/stack-structures.zig");
pub const index_pool = @import("structures/index-pool.zig"); pub const index_pool = @import("structures/index-pool.zig");
pub const IndexPoolHandle = index_pool.TypedHandle; pub const IndexPoolHandle = index_pool.TypedHandle;
pub const IndexPool = index_pool.IndexPool; 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 concurrent_queue = @import("structures/concurrent-queue.zig");
pub const ConcurrentQueueU = concurrent_queue.ConcurrentQueueU; pub const ConcurrentQueueU = concurrent_queue.ConcurrentQueueU;
pub const ConcurrentQueueUnmanagedAdvanced = concurrent_queue.ConcurrentQueueUnmanagedAdvanced; 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 paged_vector = @import("structures/paged-vector.zig");
pub const PagedVector = paged_vector.PagedVector; 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 tag_pool = @import("structures/tag-pool.zig"); pub const tag_pool = @import("structures/tag-pool.zig");
pub const RawTag = tag_pool.RawTag; pub const RawTag = tag_pool.RawTag;
pub const TagPool = tag_pool.TagPool; pub const TagPool = tag_pool.TagPool;
@ -133,22 +79,15 @@ pub fn sharedLibNameAlloc(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
comptime { comptime {
std.testing.refAllDecls(xxd); std.testing.refAllDecls(xxd);
std.testing.refAllDecls(utils);
std.testing.refAllDecls(static_structures);
std.testing.refAllDecls(ring_queue); std.testing.refAllDecls(ring_queue);
std.testing.refAllDecls(sparse_set);
// std.testing.refAllDecls(stack_structures);
std.testing.refAllDecls(index_pool); std.testing.refAllDecls(index_pool);
std.testing.refAllDecls(concurrent_queue); std.testing.refAllDecls(concurrent_queue);
std.testing.refAllDecls(@import("structures/spmc-submission-queue.zig")); std.testing.refAllDecls(@import("structures/spmc-submission-queue.zig"));
std.testing.refAllDecls(string_pool);
std.testing.refAllDecls(ref_string_map);
std.testing.refAllDecls(spans); std.testing.refAllDecls(spans);
std.testing.refAllDecls(tag_pool); std.testing.refAllDecls(tag_pool);
} }
// ---- aliases ---- // ---- aliases ----
pub const ObjectHandle = SetHandle;
pub inline fn u32_to_slice(array: *u32) []u8 { pub inline fn u32_to_slice(array: *u32) []u8 {
var slice: []u8 = undefined; var slice: []u8 = undefined;
@ -172,124 +111,6 @@ pub inline fn arrayTo_u64(array: anytype) u64 {
return @as(*const u64, @ptrCast(@alignCast(&array))).*; 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 RibLab 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" { test "ringBuffer" {
std.debug.print("\nbuffer test: filling a ring buffer\n", .{}); std.debug.print("\nbuffer test: filling a ring buffer\n", .{});

View File

@ -3,18 +3,15 @@ const stats = @import("stats.zig");
// fast bump-only allocator with checkpoints, not threadsafe. for a threadsafe arena // fast bump-only allocator with checkpoints, not threadsafe. for a threadsafe arena
// use std.heap.ArenaAllocator. // use std.heap.ArenaAllocator.
//
// memory comes from a linked list of blocks taken from the backing allocator.
// blocks are never returned to the backing allocator until reset(.free_all) or
// deinit, rewound and reset blocks go to free lists and get reused.
pub const BumpArenaOptions = struct { pub const BumpArenaOptions = struct {
/// most checkpoints that can be live at once, taking more panics. // most checkpoints that can be live at once, taking more panics.
max_checkpoints: usize = 256, max_checkpoints: usize = 32,
/// tracks live checkpoints and asserts on rewinding an invalidated one. // tracks live checkpoints and asserts on rewinding an invalidated one.
// if not turned on, there are no checkpoint limits
validate_checkpoints: bool = std.debug.runtime_safety, validate_checkpoints: bool = std.debug.runtime_safety,
}; };
pub const BumpArenaAdvanced = BumpArenaAdvancedOptions(.{}); pub const BumpArena = BumpArenaAdvancedOptions(.{});
pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type { pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
return struct { return struct {
@ -79,7 +76,7 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
pub fn getStatistics(self: *@This()) stats.PoolStatistics { pub fn getStatistics(self: *@This()) stats.PoolStatistics {
return .{ return .{
.statName = "BumpArenaAdvanced", .statName = "BumpArena",
.instanceCount = self.allocCount, .instanceCount = self.allocCount,
.memoryReserved = self.reservedBytes, .memoryReserved = self.reservedBytes,
.memoryUsed = self.allocatedBytes, .memoryUsed = self.allocatedBytes,
@ -99,14 +96,10 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
} }
/// Saves the current write position. Rewind with `defer checkpoint.rewind()`; /// Saves the current write position. Rewind with `defer checkpoint.rewind()`;
/// memory allocated after the checkpoint is invalid once it is rewound.
/// Checkpoints may be rewound in any order and more than once. Rewinding one
/// invalidates every checkpoint taken after it, and reset invalidates all.
/// Checkpoints that are never rewound are simply dropped.
pub fn checkpoint(self: *Self) Checkpoint { pub fn checkpoint(self: *Self) Checkpoint {
self.next_id += 1; self.next_id += 1;
if (options.validate_checkpoints) { if (options.validate_checkpoints) {
if (self.live_len == options.max_checkpoints) @panic("BumpArenaAdvanced: too many live checkpoints, raise max_checkpoints"); if (self.live_len == options.max_checkpoints) @panic("BumpArena: too many live checkpoints, raise max_checkpoints");
self.live[self.live_len] = self.next_id; self.live[self.live_len] = self.next_id;
self.live_len += 1; self.live_len += 1;
} }
@ -122,8 +115,8 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
fn rewind(self: *Self, cp: Checkpoint) void { fn rewind(self: *Self, cp: Checkpoint) void {
if (options.validate_checkpoints) { if (options.validate_checkpoints) {
while (self.live_len > 0 and self.live[self.live_len - 1] > cp.id) self.live_len -= 1; while (self.live_len > 0 and self.live[self.live_len - 1] > cp.id)
// the checkpoint was invalidated by rewinding an older one, or by reset. self.live_len -= 1;
std.debug.assert(self.live_len > 0 and self.live[self.live_len - 1] == cp.id); std.debug.assert(self.live_len > 0 and self.live[self.live_len - 1] == cp.id);
} }
@ -166,8 +159,6 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
return block.data() + offset; return block.data() + offset;
} }
// Offset of a `len` byte allocation after the block's used bytes, or null
// if it does not fit. Aligns the address rather than the offset.
fn fitInBlock(block: *Block, len: usize, alignment: std.mem.Alignment) ?usize { fn fitInBlock(block: *Block, len: usize, alignment: std.mem.Alignment) ?usize {
if (len > block.size) return null; if (len > block.size) return null;
const base = @intFromPtr(block.data()); const base = @intFromPtr(block.data());
@ -180,7 +171,6 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
return std.math.log2(size) - std.math.log2(BlockSize); return std.math.log2(size) - std.math.log2(BlockSize);
} }
// a free block with at least `size` usable bytes, or a new one from the backing allocator.
fn acquireBlock(self: *@This(), size: usize, ret_addr: usize) ?*Block { fn acquireBlock(self: *@This(), size: usize, ret_addr: usize) ?*Block {
for (self.free_blocks[sizeClass(size)..]) |*head| { for (self.free_blocks[sizeClass(size)..]) |*head| {
if (head.*) |block| { if (head.*) |block| {
@ -196,7 +186,6 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
return block; return block;
} }
// moves a block to its free list, it stays allocated.
fn retireBlock(self: *@This(), block: *Block) void { fn retireBlock(self: *@This(), block: *Block) void {
poison(block, 0); poison(block, 0);
const class = sizeClass(block.size); const class = sizeClass(block.size);
@ -281,82 +270,15 @@ pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
}; };
} }
pub const BumpCheckpoint = BumpArenaAdvanced.Checkpoint; pub const BumpCheckpoint = BumpArena.Checkpoint;
// mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints,
// rewinding would release other threads' allocations.
/// Deprecated: use std.heap.ArenaAllocator, its allocator is lock-free and threadsafe.
pub const BumpArenaThreaded = struct {
arena: BumpArenaAdvanced,
io_context: std.Io,
mutex: std.Io.Mutex,
pub const vtable: std.mem.Allocator.VTable = .{
.alloc = alloc,
.free = BumpArenaAdvanced.free,
.resize = BumpArenaAdvanced.resize,
.remap = std.mem.Allocator.noRemap,
};
pub fn usage(self: *@This()) usize {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
return self.arena.usage();
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
var rv = self.arena.getStatistics();
rv.statName = "BumpArenaThreaded";
return rv;
}
pub fn init(backing: std.mem.Allocator, io_context: std.Io) @This() {
return .{
.arena = .init(backing),
.io_context = io_context,
.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.arena.deinit();
}
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());
return self.arena.allocBytes(len, ptr_align, ret_addr);
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return .{ .ptr = self, .vtable = &vtable };
}
pub fn reset(self: *@This(), mode: BumpArenaAdvanced.ResetMode) void {
self.mutex.lockUncancelable(self.io());
defer self.mutex.unlock(self.io());
self.arena.reset(mode);
}
};
test "bump-it-uppp" { test "bump-it-uppp" {
var arena = BumpArenaAdvanced.init(std.testing.allocator); var arena = BumpArena.init(std.testing.allocator);
defer arena.deinit(); defer arena.deinit();
} }
test "reset clears usage" { test "reset clears usage" {
var arena = BumpArenaAdvanced.init(std.testing.allocator); var arena = BumpArena.init(std.testing.allocator);
defer arena.deinit(); defer arena.deinit();
const allocator = arena.allocator(); const allocator = arena.allocator();

View File

@ -1,11 +1,8 @@
const std = @import("std"); const std = @import("std");
const utils = @import("utils.zig");
const ArrayList = std.ArrayList; const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged; const ArrayListUnmanaged = std.ArrayListUnmanaged;
const asserts = utils.asserts;
const Atomic = std.atomic.Value; const Atomic = std.atomic.Value;
pub const ConcurrentQueueError = error{ pub const ConcurrentQueueError = error{
@ -124,9 +121,6 @@ pub fn ConcurrentQueueUnmanagedAdvanced(comptime T: type, comptime opts: struct
if (opts.debug) if (opts.debug)
std.log.warn("count {d}", .{head - tail}); 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; return head - tail;
} }
@ -157,13 +151,15 @@ test "concurrent queue basic correctness test" {
try y.push(.{ .x = 2 }); try y.push(.{ .x = 2 });
try y.push(.{ .x = 1 }); 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() }); try std.testing.expect(y.count() == 4);
// 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();
_ = 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() }); try std.testing.expect(y.count() == 0);
// 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); var x = try ConcurrentQueueU(Info).initCapacity(allocator, 12);
defer x.deinit(allocator); defer x.deinit(allocator);
@ -265,14 +261,7 @@ test "concurrent queue multiple producer single consumer" {
startTime / @as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)))) * 1000 * 1000, startTime / @as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)))) * 1000 * 1000,
}); });
try utils.assertf( try std.testing.expect(poppedCount == pushedCountResults.load(.seq_cst));
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 { fn test_getTime(io: std.Io) f64 {

View File

@ -1,306 +0,0 @@
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 = .empty,
};
_ = 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

@ -82,7 +82,7 @@ pub const ScopesContext = struct {
} }
// creates a very simple scope, the only thing it does is store the timestamp, and move on // creates a very simple scope, the only thing it does is store the timestamp, and move on
pub fn stampScope(self: *@This()) TimingScope { pub fn newScope(self: *@This()) TimingScope {
return .{ return .{
.startTsc = timestampTicks(), .startTsc = timestampTicks(),
.endTsc = null, .endTsc = null,
@ -140,7 +140,7 @@ test "calibrate scoes" {
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
{ {
var scope = scopes.stampScope(); var scope = scopes.newScope();
_ = countTo1Billion(); _ = countTo1Billion();
scope.end(); scope.end();
@ -148,13 +148,13 @@ test "calibrate scoes" {
} }
{ {
var z = scopes.stampScope(); var z = scopes.newScope();
defer z.end(); defer z.end();
_ = countTo1Million(); _ = countTo1Million();
} }
{ {
var z = scopes.stampScope(); var z = scopes.newScope();
defer z.end(); defer z.end();
_ = countTo1Million(); _ = countTo1Million();
} }

View File

@ -1,658 +0,0 @@
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

@ -1,170 +0,0 @@
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

@ -1,33 +0,0 @@
{
"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

@ -1,6 +1,7 @@
const std = @import("std"); const std = @import("std");
const PagedVector = @import("paged-vector.zig").PagedVector; const PagedVector = @import("paged-vector.zig").PagedVector;
// span 'allocator' doesn't actually allocate anything. I use this to allocate/free my index/vertex buffers
pub const Span = struct { pub const Span = struct {
start: u32, start: u32,
size: u32, size: u32,

View File

@ -1,885 +0,0 @@
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

@ -9,10 +9,8 @@ pub const Config = struct {
ChunkSize: usize = 256, ChunkSize: usize = 256,
}; };
/// Single-producer, multiple-consumer batch mailbox. Keep its address stable. /// Single-producer, multiple-consumer batch mailbox.
/// The producer pushes values then calls submit(). Each consumer supplies its /// https://peterino.com/CommitQueue%20-%20A%20turn%20based%20Queue%20for%20Reduced%20Contention.html
/// 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 { pub fn CommitQueue(comptime T: type, comptime config: Config) type {
if (config.ChunkSize == 0 or config.ChunkSize > std.math.maxInt(u24)) if (config.ChunkSize == 0 or config.ChunkSize > std.math.maxInt(u24))
@compileError("ChunkSize must be between 1 and 16777215"); @compileError("ChunkSize must be between 1 and 16777215");
@ -100,8 +98,6 @@ pub fn CommitQueue(comptime T: type, comptime config: Config) type {
}; };
} }
// 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 { fn drainTestQueue(queue: anytype) void {
var output: [@TypeOf(queue.*).ChunkSize]@TypeOf(queue.*).Item = undefined; var output: [@TypeOf(queue.*).ChunkSize]@TypeOf(queue.*).Item = undefined;
while (queue.maybeTake(&output).len != 0) {} while (queue.maybeTake(&output).len != 0) {}
@ -164,8 +160,7 @@ test "spmc flush requires both zero entries and zero reader pins" {
var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator); var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator);
defer queue.deinit(); defer queue.deinit();
defer storeTestState(&queue, .{}, .monotonic); 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{ for ([_]PackedState{
.{ .remaining_items = 1 }, .{ .remaining_items = 1 },
.{ .active_readers = 1 }, .{ .active_readers = 1 },

View File

@ -1,70 +0,0 @@
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

@ -1,832 +0,0 @@
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("lab");
defer joined.drop();
try std.testing.expectEqualStrings("riblab", 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

@ -1,226 +0,0 @@
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"));
}

View File

@ -74,7 +74,7 @@ fn getNextLine(start: *usize, stride: usize, bytes: []const u8) ?[]const u8 {
return s; return s;
} }
pub fn xxdWrite2(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) !void { pub fn xxdWrite(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) !void {
if (options.wordSize % 8 != 0 or options.wordSize == 0) return error.WordSizeNotByteAlignedUnsupported; if (options.wordSize % 8 != 0 or options.wordSize == 0) return error.WordSizeNotByteAlignedUnsupported;
if (options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions; if (options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions;
@ -269,7 +269,7 @@ pub fn xxdWriteAscii(writer: *std.Io.Writer, bytes: []const u8, options: XxdOpti
var ascii_options = options; var ascii_options = options;
ascii_options.showAscii = true; ascii_options.showAscii = true;
try xxdWrite2(writer, bytes, ascii_options); try xxdWrite(writer, bytes, ascii_options);
} }
inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions, op: ColorOp) std.Io.Writer.Error!void { inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions, op: ColorOp) std.Io.Writer.Error!void {
@ -281,6 +281,7 @@ inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions,
try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] }); try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] });
} }
/// std.debug helper functions
/// warning! needs 64k on your stack /// warning! needs 64k on your stack
pub fn printBytes(bytes: []const u8, options: XxdOptions) void { pub fn printBytes(bytes: []const u8, options: XxdOptions) void {
var workBuffer: [64 * 1024]u8 = undefined; var workBuffer: [64 * 1024]u8 = undefined;
@ -303,6 +304,5 @@ pub inline fn print(bytes: []const u8, baseAddress: usize) void {
pub inline fn printStruct(s: anytype) void { pub inline fn printStruct(s: anytype) void {
std.debug.print("{s}: size:{d} bytes\n\n", .{ @typeName(@TypeOf(s)), @sizeOf(@TypeOf(s)) }); std.debug.print("{s}: size:{d} bytes\n\n", .{ @typeName(@TypeOf(s)), @sizeOf(@TypeOf(s)) });
print(std.mem.asBytes(&s), 0); print(std.mem.asBytes(&s), 0);
} }