~alva/zig-bare

3195d1ae8ca7e646831b643be870ee3a0a446abd — Alva 4 months ago 6653ce8
Simplify and fix a bug in `readHashMap`
2 files changed, 17 insertions(+), 5 deletions(-)

M src/bare.zig
M src/test.zig
M src/bare.zig => src/bare.zig +7 -5
@@ 32,7 32,7 @@ pub const Reader = struct {
            .Bool => self.readBool(stream),
            .Struct =>
                if (comptime isHashMap(T))
                    self.readHashMap(HashMapKeyType(T), HashMapValueType(T), stream)
                    self.readHashMap(T, stream)
                else
                    self.readStruct(T, stream),
            .Enum => self.readEnum(T, stream),


@@ 178,15 178,17 @@ pub const Reader = struct {

    fn readHashMap(
        self: *Self,
        comptime K: type,
        comptime V: type,
        comptime T: type,
        stream: var
    ) !std.AutoHashMap(K, V) {
    ) !T {
        const K = HashMapKeyType(T);
        const V = HashMapValueType(T);

        if (comptime !isValidHashMapKeyType(K))
            @compileError("unsupported hashmap key type");

        var i = try self.readVarUint(stream);
        var map = std.AutoHashMap(K, V).init(&self.arena.allocator);
        var map = T.init(&self.arena.allocator);
        try map.ensureCapacity(i);

        while (i != 0) : (i -= 1) {

M src/test.zig => src/test.zig +10 -0
@@ 187,6 187,16 @@ test "read map[u8]u8" {
    expectEqual((map.get(3) orelse unreachable).value, 4);
}

test "read map[string]u8" {
    var r = Reader.init(testing.allocator);
    defer r.deinit();
    const T = std.HashMap([]const u8, u8, std.hash_map.hashString, std.hash_map.eqlString);
    const map = try r.read(T,
        io.fixedBufferStream("\x02\x04zomg\x04\x03lol\x02").inStream());
    expectEqual((map.get("lol") orelse unreachable).value, 2);
    expectEqual((map.get("zomg") orelse unreachable).value, 4);
}

test "read tagged union" {
    const Foo = union(enum) { a: i64, b: bool, c: u8 };
    const res = try Reader.init(testing.allocator).read(Foo,