| ... | @@ -48,6 +48,22 @@ pub fn values(comptime E: type) []const E { | ... | @@ -48,6 +48,22 @@ pub fn values(comptime E: type) []const E { |
| 48 | return comptime valuesFromFields(E, @typeInfo(E).Enum.fields); | 48 | return comptime valuesFromFields(E, @typeInfo(E).Enum.fields); |
| 49 | } | 49 | } |
| 50 | | 50 | |
| | 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. |
| | 54 | pub 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 | |
| | 60 | test 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 | |
| 51 | /// Determines the length of a direct-mapped enum array, indexed by | 67 | /// Determines the length of a direct-mapped enum array, indexed by |
| 52 | /// @intCast(usize, @enumToInt(enum_value)). | 68 | /// @intCast(usize, @enumToInt(enum_value)). |
| 53 | /// If the enum is non-exhaustive, the resulting length will only be enough | 69 | /// If the enum is non-exhaustive, the resulting length will only be enough |