Skip to content

Instantly share code, notes, and snippets.

@SuperAuguste
Created May 5, 2024 18:38
Show Gist options
  • Save SuperAuguste/d54b11cba325a1034cc827652c0ea1d2 to your computer and use it in GitHub Desktop.
Save SuperAuguste/d54b11cba325a1034cc827652c0ea1d2 to your computer and use it in GitHub Desktop.
Type IDs
const std = @import("std");
pub const TypeIdStore = struct {
types: []const type = &.{},
pub fn id(comptime store: *TypeIdStore, comptime T: type) u32 {
inline for (store.types, 0..) |t, i| {
if (t == T) return @intCast(i);
}
store.types = store.types ++ &[1]type{T};
return store.types.len - 1;
}
};
test {
comptime var store = TypeIdStore{};
try std.testing.expectEqual(0, comptime store.id(u8));
try std.testing.expectEqual(1, comptime store.id(u16));
try std.testing.expectEqual(0, comptime store.id(u8));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment