1
Fork 0
turbonss/lib/Group.zig

81 lines
2.2 KiB
Zig

const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const BufSet = std.BufSet;
const Group = @This();
gid: u32,
name: []const u8,
members: BufSet,
pub fn clone(self: *const Group, allocator: Allocator) Allocator.Error!Group {
var name = try allocator.dupe(u8, self.name);
return Group{
.gid = self.gid,
.name = name,
.members = try self.members.cloneWithAllocator(allocator),
};
}
pub fn deinit(self: *Group, allocator: Allocator) void {
allocator.free(self.name);
self.members.deinit();
self.* = undefined;
}
// someMembers constructs a bufset from an allocator and a list of strings.
pub fn someMembers(
allocator: Allocator,
members: []const []const u8,
) Allocator.Error!BufSet {
var bufset = BufSet.init(allocator);
errdefer bufset.deinit();
for (members) |member|
try bufset.insert(member);
return bufset;
}
// cloneArray clones an array of strings. This may be needed
// to change members to []const []const u8
fn cloneArray(allocator: Allocator, arr: []const []const u8) error{OutOfMemory}![]const []const u8 {
const total_len = blk: {
var sum: usize = 0;
for (arr) |elem| sum += elem.len;
break :blk sum;
};
var buf = try allocator.alloc(u8, total_len);
var ret = try allocator.alloc([]const u8, arr.len);
ret.len = arr.len;
for (arr) |elem, i| {
const old_len = buf.len;
mem.copy(u8, buf[old_len..], elem);
ret[i] = buf[old_len .. old_len + elem.len];
}
return ret;
}
const testing = std.testing;
test "Group.clone" {
var allocator = testing.allocator;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var members = BufSet.init(allocator);
try members.insert("member1");
try members.insert("member2");
defer members.deinit();
var cloned = try members.cloneWithAllocator(arena.allocator());
cloned.remove("member1");
try cloned.insert("member4");
try testing.expect(members.contains("member1"));
try testing.expect(!members.contains("member4"));
try testing.expect(!cloned.contains("member1"));
try testing.expect(cloned.contains("member4"));
}