~alva/zig-bare

dba916ae777430261fe2ee1fce7cccd23c248b7e — Alva 4 months ago d39721d
Handle maps with 0 items
2 files changed, 25 insertions(+), 6 deletions(-)

M src/bare.zig
M src/test.zig
M src/bare.zig => src/bare.zig +8 -5
@@ 189,12 189,15 @@ pub const Reader = struct {

        var i = try self.readVarUint(stream);
        var map = T.init(&self.arena.allocator);
        try map.ensureCapacity(i);

        while (i != 0) : (i -= 1) {
            const key = try self.read(K, stream);
            const val = try self.read(V, stream);
            _ = map.putAssumeCapacity(key, val);
        if (i != 0) {
            try map.ensureCapacity(i);

            while (i != 0) : (i -= 1) {
                const key = try self.read(K, stream);
                const val = try self.read(V, stream);
                _ = map.putAssumeCapacity(key, val);
            }
        }

        return map;

M src/test.zig => src/test.zig +17 -1
@@ 179,6 179,14 @@ test "read u8 slice" {
    expectEqualSlices(u8, expected[0..], res[0..]);
}

test "read 0-length slice" {
    const res = try Reader.init(testing.allocator).read([]const u8,
        io.fixedBufferStream("\x00").inStream());
    defer testing.allocator.free(res);
    const expected = [_]u8{};
    expectEqualSlices(u8, expected[0..], res[0..]);
}

test "read map[u8]u8" {
    var r = Reader.init(testing.allocator);
    defer r.deinit();


@@ 187,6 195,13 @@ test "read map[u8]u8" {
    expectEqual((map.get(3) orelse unreachable).value, 4);
}

test "read map[u8]u8 with 0 items" {
    var r = Reader.init(testing.allocator);
    defer r.deinit();
    const map = try r.read(std.AutoHashMap(u8, u8), io.fixedBufferStream("\x00").inStream());
    expectEqual(map.size, 0);
}

test "read map[string]u8" {
    var r = Reader.init(testing.allocator);
    defer r.deinit();


@@ 517,7 532,8 @@ test "round trip tagged union" {

test "bare.Reader frees its memory" {
    var r = Reader.init(testing.allocator);
    const map = try r.read(std.AutoHashMap(u8, u8), io.fixedBufferStream("\x02\x01\x02\x03\x04").inStream());
    _ = try r.read(std.AutoHashMap(u8, u8), io.fixedBufferStream("\x02\x01\x02\x03\x04").inStream());
    _ = try r.read([]const u8, io.fixedBufferStream("\x04\x01\x02\x03\x04").inStream());
    defer r.deinit();
    // testing.allocator will yell if memory is leaked
}