From 73662d675ab3235bb21c14b61ddce643f8585c9f Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Tue, 19 Jul 2022 02:22:19 -0700 Subject: [PATCH] Fully implement api free() --- src/main/api.zig | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/main/api.zig b/src/main/api.zig index d4d26e9..5145524 100644 --- a/src/main/api.zig +++ b/src/main/api.zig @@ -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, } }