Group.members: fake sentinel at clone time

This commit is contained in:
Motiejus Jakštys 2022-04-03 14:52:06 +03:00 committed by Motiejus Jakštys
parent 5704deb6b3
commit d4d3729bf0

View File

@ -7,18 +7,23 @@ const Group = @This();
gid: u32, gid: u32,
name: [:0]const u8, name: [:0]const u8,
// // should be [:null]const ?[:0]const u8, but it crashes the compiler. See
members: [:null]const ?[:0]const u8, // https://github.com/ziglang/zig/issues/7517.
// members[members.len] is always null for cloned groups. Once the bug
// in the compiler is fixed, we should update the return type here.
members: []const ?[:0]const u8,
pub fn clone(self: *const Group, allocator: Allocator) Allocator.Error!Group { pub fn clone(self: *const Group, allocator: Allocator) Allocator.Error!Group {
var members = try allocator.allocSentinel(?[:0]const u8, self.members.len, null); var members = try allocator.alloc(?[:0]const u8, self.members.len + 1);
errdefer allocator.free(members); errdefer allocator.free(members);
members.len = self.members.len; members.len = self.members.len + 1;
for (self.members) |member, i| { for (self.members) |member, i| {
const member_name = member.?; members[i] = try allocator.dupeZ(u8, member.?);
members[i] = try allocator.dupeZ(u8, member_name); errdefer allocator.free(members[i]);
} }
members[self.members.len] = null;
members.len = self.members.len;
return Group{ return Group{
.gid = self.gid, .gid = self.gid,
@ -46,7 +51,7 @@ test "Group.clone" {
var group = Group{ var group = Group{
.gid = 1, .gid = 1,
.name = "foo", .name = "foo",
.members = &[_:null]?[:0]const u8{ member1, "member2", null }, .members = &[_:null]?[:0]const u8{ member1, "member2" },
}; };
var cloned = try group.clone(testing.allocator); var cloned = try group.clone(testing.allocator);