2017-04-03 22:52:20 -07:00
|
|
|
const HashMap = @import("hash_map.zig").HashMap;
|
|
|
|
const mem = @import("mem.zig");
|
|
|
|
const Allocator = mem.Allocator;
|
|
|
|
|
|
|
|
pub const BufSet = struct {
|
|
|
|
hash_map: BufSetHashMap,
|
|
|
|
|
|
|
|
const BufSetHashMap = HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8);
|
|
|
|
|
2017-10-13 06:31:03 -07:00
|
|
|
pub fn init(a: &Allocator) -> BufSet {
|
2017-04-03 22:52:20 -07:00
|
|
|
var self = BufSet {
|
2017-10-13 06:31:03 -07:00
|
|
|
.hash_map = BufSetHashMap.init(a),
|
2017-04-03 22:52:20 -07:00
|
|
|
};
|
|
|
|
return self;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn deinit(self: &BufSet) {
|
2017-04-06 02:34:04 -07:00
|
|
|
var it = self.hash_map.iterator();
|
2017-04-03 22:52:20 -07:00
|
|
|
while (true) {
|
|
|
|
const entry = it.next() ?? break;
|
|
|
|
self.free(entry.key);
|
|
|
|
}
|
|
|
|
|
|
|
|
self.hash_map.deinit();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn put(self: &BufSet, key: []const u8) -> %void {
|
|
|
|
if (self.hash_map.get(key) == null) {
|
2018-01-07 13:51:46 -08:00
|
|
|
const key_copy = try self.copy(key);
|
2018-01-23 20:08:09 -08:00
|
|
|
errdefer self.free(key_copy);
|
2018-01-07 13:51:46 -08:00
|
|
|
_ = try self.hash_map.put(key_copy, {});
|
2017-04-03 22:52:20 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn delete(self: &BufSet, key: []const u8) {
|
|
|
|
const entry = self.hash_map.remove(key) ?? return;
|
|
|
|
self.free(entry.key);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn count(self: &const BufSet) -> usize {
|
|
|
|
return self.hash_map.size;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn iterator(self: &const BufSet) -> BufSetHashMap.Iterator {
|
2017-04-06 02:34:04 -07:00
|
|
|
return self.hash_map.iterator();
|
2017-04-03 22:52:20 -07:00
|
|
|
}
|
|
|
|
|
2017-10-13 06:31:03 -07:00
|
|
|
pub fn allocator(self: &const BufSet) -> &Allocator {
|
|
|
|
return self.hash_map.allocator;
|
|
|
|
}
|
|
|
|
|
2017-04-03 22:52:20 -07:00
|
|
|
fn free(self: &BufSet, value: []const u8) {
|
|
|
|
// remove the const
|
2017-05-19 07:39:59 -07:00
|
|
|
const mut_value = @ptrCast(&u8, value.ptr)[0..value.len];
|
2017-04-03 22:52:20 -07:00
|
|
|
self.hash_map.allocator.free(mut_value);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn copy(self: &BufSet, value: []const u8) -> %[]const u8 {
|
2018-01-07 13:51:46 -08:00
|
|
|
const result = try self.hash_map.allocator.alloc(u8, value.len);
|
2017-04-03 22:52:20 -07:00
|
|
|
mem.copy(u8, result, value);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|