Does not do deduplication (only because there's no chance of duplicate strings in this instance).
const StringTable = struct
const StringTable = struct {
bytes: std.ArrayList(u8) = .empty,
pub fn deinit(self: *StringTable, allocator: Allocator) void {
self.bytes.deinit(allocator);
}
/// Returns the byte offset of the string in the string table
pub fn put(self: *StringTable, allocator: Allocator, string: []const u8) !u32 {
const null_terminated_len = string.len + 1;
const start_offset = self.totalByteLength();
if (start_offset + null_terminated_len > std.math.maxInt(u32)) {
return error.StringTableOverflow;
}
try self.bytes.ensureUnusedCapacity(allocator, null_terminated_len);
self.bytes.appendSliceAssumeCapacity(string);
self.bytes.appendAssumeCapacity(0);
return start_offset;
}
/// Returns the total byte count of the string table, including the byte count of the size field
pub fn totalByteLength(self: StringTable) u32 {
return @intCast(4 + self.bytes.items.len);
}
}