Created
May 5, 2024 18:38
-
-
Save SuperAuguste/d54b11cba325a1034cc827652c0ea1d2 to your computer and use it in GitHub Desktop.
Type IDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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