Skip to content

Instantly share code, notes, and snippets.

@notcancername
Created August 5, 2024 20:11
Show Gist options
  • Save notcancername/5857958eb9e568450076c662fdf9fa6e to your computer and use it in GitHub Desktop.
Save notcancername/5857958eb9e568450076c662fdf9fa6e to your computer and use it in GitHub Desktop.
zig function to report on the size of containers
const std = @import("std");
pub fn sizeReport(comptime T: type, comptime indent: []const u8) []const u8 {
comptime {
var result: []const u8 = "";
result = result ++ std.fmt.comptimePrint("{s}size of {s} is {d} bytes ({d} bits)\n", .{indent, @typeName(T), @sizeOf(T), @bitSizeOf(T)});
switch (@typeInfo(T)) {
.Struct => |s| {
result = result ++ std.fmt.comptimePrint("{s}field report ({s}):\n", .{indent, @tagName(s.layout)});
for (s.fields) |field| {
if (!field.is_comptime and @sizeOf(field.type) != 0) {
result = result ++ sizeReport(field.type, indent ++ std.fmt.comptimePrint("{s} a({d}): ", .{field.name, field.alignment}));
}
}
result = result ++ "\n";
},
.Union => |u| {
result = result ++ std.fmt.comptimePrint("{s}field report ({s}):\n{s}\n", .{indent, @tagName(u.layout), sizeReport(u.tag_type orelse void, indent ++ "tag: ")});
for (u.fields) |field| {
if (@sizeOf(field.type) != 0) {
result = result ++ sizeReport(field.type, indent ++ std.fmt.comptimePrint("{s} a({d}): ", .{field.name, field.alignment}));
}
}
result = result ++ "\n";
},
.Array => |a| {
result = result ++ std.fmt.comptimePrint("{s}array {s}", .{indent, sizeReport(a.child, indent ++ "child: ")});
result = result ++ "\n";
},
else => {},
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment