Created
April 8, 2023 17:16
-
-
Save CraigglesO/30bdcd2aad83414a1248eb21575b0681 to your computer and use it in GitHub Desktop.
Showing strange behavior with zig StringHashMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const testing = std.testing; | |
const ArrayList = std.ArrayList; | |
const StringHashMap = std.StringHashMap; | |
pub const Protobuf = struct { | |
buf: ArrayList(u8), | |
pos: usize, | |
len: usize, | |
allocator: std.mem.Allocator, | |
const Self = @This(); | |
pub fn init (input: []const u8, allocator: std.mem.Allocator) !Protobuf { | |
var buf = ArrayList(u8).init(allocator); | |
try buf.appendSlice(input); | |
return .{ | |
.buf = buf, | |
.pos = 0, | |
.len = buf.items.len, | |
.allocator = allocator, | |
}; | |
} | |
pub fn getValue(self: *Self) u8 { | |
defer { self.pos += 1; } | |
return self.buf.items[self.pos]; | |
} | |
}; | |
pub const A = struct { | |
pbf: Protobuf, | |
data: StringHashMap(B), | |
arena: std.heap.ArenaAllocator, | |
const Self = @This(); | |
pub fn init (buffer: []const u8, child_allocator: std.mem.Allocator) !A { | |
var arena = std.heap.ArenaAllocator.init(child_allocator); | |
var allocator = arena.allocator(); | |
var pbf = try Protobuf.init(buffer, allocator); | |
var a = A{ | |
.pbf = pbf, | |
.data = StringHashMap(B).init(allocator), | |
.arena = arena, | |
}; | |
try a.data.put("testA", B.init(&pbf)); | |
try a.data.put("testB", B.init(&pbf)); | |
return a; | |
} | |
pub fn deinit (self: *Self) void { | |
self.arena.deinit(); | |
} | |
}; | |
pub const B = struct { | |
pbf: *Protobuf, | |
data: ArrayList(C), | |
const Self = @This(); | |
pub fn init (pbf: *Protobuf) B { | |
return .{ | |
.pbf = pbf, | |
.data = ArrayList(C).init(pbf.allocator), | |
}; | |
} | |
pub fn getC (self: *Self) !C { | |
std.debug.print("\npbf contents: {any}", .{self.pbf.buf.items}); | |
return try C.init(self.pbf); | |
} | |
}; | |
pub const C = struct { | |
x: i32, | |
y: i32, | |
const Self = @This(); | |
pub fn init (pbf: *Protobuf) !C { | |
return .{ | |
.x = pbf.getValue(), | |
.y = pbf.getValue(), | |
}; | |
} | |
}; | |
test "run" { | |
const exampleData = [_]u8{ 0, 1, 2, 3 }; | |
var a = try A.init(&exampleData, testing.allocator); | |
defer a.deinit(); | |
var b1 = a.data.get("testA").?; | |
var c1 = try b1.getC(); | |
try testing.expectEqual(c1, C{.x = 0, .y = 1 }); | |
var b2 = a.data.get("testB").?; | |
var c2 = try b2.getC(); | |
try testing.expectEqual(c2, C{.x = 2, .y = 3 }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment