diff options
| author | Andrew Kelley <superjoe30@gmail.com> | 2018-04-11 18:27:06 -0400 |
|---|---|---|
| committer | Andrew Kelley <superjoe30@gmail.com> | 2018-04-11 18:27:06 -0400 |
| commit | ce68dda4b60914e947088e7cf0c5626ea7cebc08 (patch) | |
| tree | fca8e600e1b48862d816e5caa87f6fa5ab50d175 /std/buf_map.zig | |
| parent | 588116cacc77535137262832f1b2aa464e7a1131 (diff) | |
| parent | ed1b028276bc1d17ee5e99863dd5bf150c8aa2f7 (diff) | |
| download | zig-ce68dda4b60914e947088e7cf0c5626ea7cebc08.tar.gz zig-ce68dda4b60914e947088e7cf0c5626ea7cebc08.zip | |
Merge remote-tracking branch 'origin/master' into llvm7
Diffstat (limited to 'std/buf_map.zig')
| -rw-r--r-- | std/buf_map.zig | 51 |
1 files changed, 34 insertions, 17 deletions
diff --git a/std/buf_map.zig b/std/buf_map.zig index a58df4b2db..3e12d9a7d9 100644 --- a/std/buf_map.zig +++ b/std/buf_map.zig @@ -1,6 +1,8 @@ -const HashMap = @import("hash_map.zig").HashMap; -const mem = @import("mem.zig"); +const std = @import("index.zig"); +const HashMap = std.HashMap; +const mem = std.mem; const Allocator = mem.Allocator; +const assert = std.debug.assert; /// BufMap copies keys and values before they go into the map, and /// frees them when they get removed. @@ -28,18 +30,12 @@ pub const BufMap = struct { } pub fn set(self: &BufMap, key: []const u8, value: []const u8) !void { - if (self.hash_map.get(key)) |entry| { - const value_copy = try self.copy(value); - errdefer self.free(value_copy); - _ = try self.hash_map.put(key, value_copy); - self.free(entry.value); - } else { - const key_copy = try self.copy(key); - errdefer self.free(key_copy); - const value_copy = try self.copy(value); - errdefer self.free(value_copy); - _ = try self.hash_map.put(key_copy, value_copy); - } + self.delete(key); + const key_copy = try self.copy(key); + errdefer self.free(key_copy); + const value_copy = try self.copy(value); + errdefer self.free(value_copy); + _ = try self.hash_map.put(key_copy, value_copy); } pub fn get(self: &BufMap, key: []const u8) ?[]const u8 { @@ -66,8 +62,29 @@ pub const BufMap = struct { } fn copy(self: &BufMap, value: []const u8) ![]const u8 { - const result = try self.hash_map.allocator.alloc(u8, value.len); - mem.copy(u8, result, value); - return result; + return mem.dupe(self.hash_map.allocator, u8, value); } }; + +test "BufMap" { + var direct_allocator = std.heap.DirectAllocator.init(); + defer direct_allocator.deinit(); + + var bufmap = BufMap.init(&direct_allocator.allocator); + defer bufmap.deinit(); + + try bufmap.set("x", "1"); + assert(mem.eql(u8, ??bufmap.get("x"), "1")); + assert(1 == bufmap.count()); + + try bufmap.set("x", "2"); + assert(mem.eql(u8, ??bufmap.get("x"), "2")); + assert(1 == bufmap.count()); + + try bufmap.set("x", "3"); + assert(mem.eql(u8, ??bufmap.get("x"), "3")); + assert(1 == bufmap.count()); + + bufmap.delete("x"); + assert(0 == bufmap.count()); +} |
