I’m writing a msgpack serialization library and have something I’m struggling with. Because of the flexible type generation at comptime, I’m not sure how to detect if some field of a struct is, for example, ArrayList, so that I can serialize it as an array, not as a generic struct. Is something like that even possible?
A trick I’ve done in the past is to extract the T
you pass to ArrayList
and reinstantiate the type. Then compare if the type you get is the same as ArrayList
fn isArraylist(comptime T: type) bool {
if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "Slice"))
return false;
const Slice = T.Slice;
const ptr_info = switch (@typeInfo(Slice)) {
.pointer => |info| info,
else => return false,
};
return T == std.ArrayListAlignedUnmanaged(ptr_info.child, null) or
T == std.ArrayListAlignedUnmanaged(ptr_info.child, ptr_info.alignment) or
T == std.ArrayListAligned(ptr_info.child, null) or
T == std.ArrayListAligned(ptr_info.child, ptr_info.alignment);
}
test {
try std.testing.expect(!isArraylist(u8));
try std.testing.expect(!isArraylist([]const u8));
try std.testing.expect(isArraylist(std.ArrayList(u8)));
}
const std = @import("std");
4 Likes