update: context
This commit is contained in:
parent
e9c042a654
commit
164e68e94c
3 changed files with 131 additions and 4 deletions
51
src/context.zig
Normal file
51
src/context.zig
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
const std = @import("std");
|
||||
|
||||
pub const Value = union(enum) {
|
||||
null,
|
||||
bool: bool,
|
||||
int: i64,
|
||||
float: f64,
|
||||
string: []const u8,
|
||||
list: []const Value,
|
||||
dict: std.StringHashMapUnmanaged(Value),
|
||||
|
||||
pub fn deinit(self: Value) void {
|
||||
_ = self; // nada — a arena libera tudo
|
||||
}
|
||||
};
|
||||
|
||||
pub const Context = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
map: std.StringHashMapUnmanaged(Value),
|
||||
|
||||
pub fn init(child_allocator: std.mem.Allocator) Context {
|
||||
const arena = std.heap.ArenaAllocator.init(child_allocator);
|
||||
return .{
|
||||
.arena = arena,
|
||||
.map = .{},
|
||||
};
|
||||
}
|
||||
|
||||
pub fn allocator(self: *Context) std.mem.Allocator {
|
||||
return self.arena.allocator();
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Context) void {
|
||||
self.arena.deinit();
|
||||
}
|
||||
|
||||
pub fn set(self: *Context, key: []const u8, value: Value) !void {
|
||||
const gop = try self.map.getOrPut(self.allocator(), key);
|
||||
if (gop.found_existing) {
|
||||
// opcional: deinit value antigo se necessário
|
||||
// mas como arena libera tudo, não precisa
|
||||
} else {
|
||||
gop.key_ptr.* = try self.allocator().dupe(u8, key);
|
||||
}
|
||||
gop.value_ptr.* = value;
|
||||
}
|
||||
|
||||
pub fn get(self: *const Context, key: []const u8) ?Value {
|
||||
return self.map.get(key);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue