Fully implement api free()

This commit is contained in:
jaina heartles 2022-07-19 02:22:19 -07:00
parent 718da7b408
commit 73662d675a

View file

@ -9,15 +9,23 @@ pub const Uuid = util.Uuid;
// Frees an api struct and its fields allocated from alloc
pub fn free(alloc: std.mem.Allocator, val: anytype) void {
inline for (std.meta.fields(@TypeOf(val))) |f| {
// TODO
if (f.field_type == []u8 or f.field_type == []const u8) {
alloc.free(@field(val, f.name));
} else if (f.field_type == Uuid or f.field_type == DateTime) {
// nothing
} else {
@compileError("unsupported field type " ++ @typeName(f.field_type));
}
switch (@typeInfo(@TypeOf(val))) {
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => {
free(alloc, val.*);
alloc.destroy(val);
},
.Slice => {
for (val) |elem| free(alloc, elem);
alloc.free(val);
},
else => unreachable,
},
.Struct => inline for (std.meta.fields(@TypeOf(val))) |f| free(alloc, @field(val, f.name)),
.Array => for (val) |elem| free(alloc, elem),
.Optional => if (val) |opt| free(alloc, opt),
.Bool, .Int, .Float, .Enum => {},
else => unreachable,
}
}