authorgravatar for twostepted@gmail.comTravis Staloch <twostepted@gmail.com> 2023-05-02 16:10:59-07:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-05-10 16:07:34+03:00
log5d1e69389c3acbd854cbc56002c1100af5b6e140
treeadeb65276f9914c20b3e01af248d9ed252023d25
parent37f56a425949ffb71ec412e298ccd70748c65cc3

std.enums: add tagName()

This is safe alternative to `@tagName()` for non-exhaustive enums that doesn't panic when given an enum value that has no tag.

1 files changed, 16 insertions(+), 0 deletions(-)

lib/std/enums.zig+16
......@@ -48,6 +48,22 @@ pub fn values(comptime E: type) []const E {
4848 return comptime valuesFromFields(E, @typeInfo(E).Enum.fields);
4949}
5050
51/// A safe alternative to @tagName() for non-exhaustive enums that doesn't
52/// panic when `e` has no tagged value.
53/// Returns the tag name for `e` or null if no tag exists.
54pub fn tagName(comptime E: type, e: E) ?[]const u8 {
55 return inline for (@typeInfo(E).Enum.fields) |f| {
56 if (@enumToInt(e) == f.value) break f.name;
57 } else null;
58}
59
60test tagName {
61 const E = enum(u8) { a, b, _ };
62 try testing.expect(tagName(E, .a) != null);
63 try testing.expectEqualStrings("a", tagName(E, .a).?);
64 try testing.expect(tagName(E, @intToEnum(E, 42)) == null);
65}
66
5167/// Determines the length of a direct-mapped enum array, indexed by
5268/// @intCast(usize, @enumToInt(enum_value)).
5369/// If the enum is non-exhaustive, the resulting length will only be enough