chore: initial commit

This commit is contained in:
Rekai Nyangadzayi Musuka 2023-04-10 22:37:12 -05:00
commit 5e630120f2
5 changed files with 298 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
zig-cache/
zig-out/
.vscode/

67
build.zig Normal file
View File

@ -0,0 +1,67 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "trie",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
exe.install();
// This *creates* a RunStep in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = exe.run();
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing.
const exe_tests = b.addTest(.{
.root_source_file = .{ .path = "src/tests.zig" },
.target = target,
.optimize = optimize,
});
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&exe_tests.step);
}

210
src/HashArrayMappedTrie.zig Normal file
View File

@ -0,0 +1,210 @@
//! Hash Array Mapped Trie
//! https://idea.popcount.org/2012-07-25-introduction-to-hamt/
const std = @import("std");
// const Token = @import("Token.zig");
const Allocator = std.mem.Allocator;
const HashArrayMappedTrie = @This();
const t = 5;
const table_size = std.math.powi(u32, 2, t) catch unreachable;
root: [table_size]?*Node,
allocator: Allocator,
const Node = union(enum) { kv: Pair, table: Table };
const Pair = struct { key: []const u8, value: void };
const Table = struct { map: u32 = 0, base: [*]Node };
pub fn init(allocator: Allocator) !HashArrayMappedTrie {
return .{
.root = [_]?*Node{null} ** table_size,
.allocator = allocator,
};
}
pub fn deinit(self: *HashArrayMappedTrie) void {
for (self.root) |node| {
if (node == null) continue;
deinitRecurse(self.allocator, node.?);
}
}
fn deinitRecurse(allocator: Allocator, node: *Node) void {
switch (node.*) {
.kv => allocator.destroy(node),
else => {},
}
}
fn amtIdx(comptime T: type, bitset: T, offset: u16) std.math.Log2Int(T) {
const L2I = std.math.Log2Int(T);
const shift_amt = @intCast(L2I, @typeInfo(T).Int.bits - offset);
return @truncate(L2I, bitset >> shift_amt);
}
pub fn search(self: *HashArrayMappedTrie, key: []const u8) ?Pair {
const bitset = hash(key);
// most siginificant t bits from hash
var hash_offset: u5 = t;
var current: *Node = self.root[amtIdx(u32, bitset, hash_offset)] orelse return null;
while (true) {
switch (current.*) {
.table => |table| {
hash_offset += t;
const mask = @as(u32, 1) << amtIdx(u32, bitset, hash_offset);
if (table.map & mask != 0) {
const idx = @popCount(table.map & (mask - 1));
current = &table.base[idx];
} else return null; // hash table entry is empty
},
.kv => |pair| {
if (!std.mem.eql(u8, pair.key, key)) return null;
return pair;
},
}
}
}
pub fn insert(self: *HashArrayMappedTrie, comptime key: []const u8, value: void) !void {
const bitset = hash(key);
// most siginificant t bits from hash
var hash_offset: u5 = t;
const root_idx = amtIdx(u32, bitset, hash_offset);
var current: *Node = self.root[root_idx] orelse {
// node in root table is empty, place the KV here
const node = try self.allocator.create(Node);
node.* = .{ .kv = .{ .key = key, .value = value } };
self.root[root_idx] = node;
return;
};
while (true) {
const mask = @as(u32, 1) << amtIdx(u32, bitset, hash_offset);
switch (current.*) {
.table => |*table| {
if (table.map & mask == 0) {
// Empty
const old_len = @popCount(table.map);
const new_base = try self.allocator.alloc(Node, old_len + 1);
var i: u5 = 0;
for (0..@typeInfo(u32).Int.bits) |shift| {
const mask_loop = @as(u32, 1) << @intCast(u5, shift);
if (table.map & mask_loop != 0) {
defer i += 1;
const idx = @popCount(table.map & (mask_loop - 1));
const copy = if (mask == mask_loop) Node{ .kv = Pair{ .key = key, .value = value } } else table.base[idx];
new_base[i] = copy;
}
}
self.allocator.free(table.base[0..old_len]);
table.base = new_base.ptr;
table.map |= mask;
return; // inserted an elemnt into the Trie
} else {
// Found an entry in the array, continue loop (?)
const idx = @popCount(table.map & (mask - 1));
current = &table.base[idx];
hash_offset += t; // Go one layer deper
}
},
.kv => |prev_pair| {
const prev_bitset = hash(prev_pair.key);
const prev_mask = @as(u32, 1) << amtIdx(u32, prev_bitset, hash_offset);
const table = switch (std.math.order(mask, prev_mask)) {
.lt => blk: {
// there are no collisions between the two hash subsets.
const pairs = try self.allocator.alloc(Node, 2);
pairs[0] = .{ .kv = .{ .key = key, .value = value } };
pairs[1] = .{ .kv = prev_pair };
break :blk .{ .table = .{ .map = mask | prev_mask, .base = pairs.ptr } };
},
.gt => blk: {
// there are no collisions between the two hash subsets.
const pairs = try self.allocator.alloc(Node, 2);
pairs[0] = .{ .kv = prev_pair };
pairs[1] = .{ .kv = .{ .key = key, .value = value } };
break :blk .{ .table = .{ .map = mask | prev_mask, .base = pairs.ptr } };
},
.eq => blk: {
const copied_pair = try self.allocator.alloc(Node, 1);
copied_pair[0] = .{ .kv = prev_pair };
break :blk .{ .table = .{ .map = mask, .base = copied_pair.ptr } };
},
};
current.* = table;
},
}
}
}
fn walk(node: *const Node, indent: u8) void {
switch (node.*) {
.kv => |pair| std.debug.print("{}: {any}\n", .{ indent, pair }),
.table => |table| {
const len = @popCount(table.map);
for (0..len) |i| {
walk(&table.base[i], indent + 1);
}
},
}
}
fn hash(key: []const u8) u32 {
var result: u32 = 0;
for (key) |c| result |= @as(u32, 1) << @intCast(u5, c - 'a');
return result;
}
test "insert doesn't panic" {
var trie = try HashArrayMappedTrie.init(std.testing.allocator);
defer trie.deinit();
try trie.insert("hello", {});
}
test "search doesn't panic" {
var trie = try HashArrayMappedTrie.init(std.testing.allocator);
defer trie.deinit();
std.debug.assert(trie.search("hello") == null);
}
test "insert then search" {
var trie = try HashArrayMappedTrie.init(std.heap.page_allocator);
defer trie.deinit();
// Basic Usage
try trie.insert("hello", {});
const test1 = trie.search("hello").?;
try std.testing.expectEqual(Pair{ .key = "hello", .value = {} }, test1);
// Collision in Root Node
try trie.insert("helloworld", {});
const test2 = trie.search("helloworld").?;
try std.testing.expectEqual(Pair{ .key = "helloworld", .value = {} }, test2);
}

10
src/main.zig Normal file
View File

@ -0,0 +1,10 @@
const std = @import("std");
const HashArrayMappedTrie = @import("HashArrayMappedTrie.zig");
pub fn main() !void {
var trie = try HashArrayMappedTrie.init(std.heap.page_allocator);
defer trie.deinit();
try trie.insert("hello", {});
try trie.insert("helloworld", {});
}

8
src/tests.zig Normal file
View File

@ -0,0 +1,8 @@
comptime {
_ = @import("HashArrayMappedTrie.zig");
_ = @import("main.zig");
}
test {
@import("std").testing.refAllDecls(@This());
}