| ... | ... | @@ -965,18 +965,33 @@ test "intToEnum with error return" { |
| 965 | 965 | A, |
| 966 | 966 | B, |
| 967 | 967 | }; |
| 968 | const E3 = enum(i8) { A, _ }; |
| 968 | 969 | |
| 969 | 970 | var zero: u8 = 0; |
| 970 | 971 | var one: u16 = 1; |
| 971 | 972 | try testing.expect(intToEnum(E1, zero) catch unreachable == E1.A); |
| 972 | 973 | try testing.expect(intToEnum(E2, one) catch unreachable == E2.B); |
| 974 | try testing.expect(intToEnum(E3, zero) catch unreachable == E3.A); |
| 975 | try testing.expect(intToEnum(E3, 127) catch unreachable == @intToEnum(E3, 127)); |
| 976 | try testing.expect(intToEnum(E3, -128) catch unreachable == @intToEnum(E3, -128)); |
| 973 | 977 | try testing.expectError(error.InvalidEnumTag, intToEnum(E1, one)); |
| 978 | try testing.expectError(error.InvalidEnumTag, intToEnum(E3, 128)); |
| 979 | try testing.expectError(error.InvalidEnumTag, intToEnum(E3, -129)); |
| 974 | 980 | } |
| 975 | 981 | |
| 976 | 982 | pub const IntToEnumError = error{InvalidEnumTag}; |
| 977 | 983 | |
| 978 | 984 | pub fn intToEnum(comptime EnumTag: type, tag_int: anytype) IntToEnumError!EnumTag { |
| 979 | | inline for (@typeInfo(EnumTag).Enum.fields) |f| { |
| 985 | const enum_info = @typeInfo(EnumTag).Enum; |
| 986 | |
| 987 | if (!enum_info.is_exhaustive) { |
| 988 | if (std.math.cast(enum_info.tag_type, tag_int)) |tag| { |
| 989 | return @intToEnum(EnumTag, tag); |
| 990 | } |
| 991 | return error.InvalidEnumTag; |
| 992 | } |
| 993 | |
| 994 | inline for (enum_info.fields) |f| { |
| 980 | 995 | const this_tag_value = @field(EnumTag, f.name); |
| 981 | 996 | if (tag_int == @enumToInt(this_tag_value)) { |
| 982 | 997 | return this_tag_value; |