| ... | @@ -965,18 +965,33 @@ test "intToEnum with error return" { | ... | @@ -965,18 +965,33 @@ test "intToEnum with error return" { |
| 965 | A, | 965 | A, |
| 966 | B, | 966 | B, |
| 967 | }; | 967 | }; |
| | 968 | const E3 = enum(i8) { A, _ }; |
| 968 | | 969 | |
| 969 | var zero: u8 = 0; | 970 | var zero: u8 = 0; |
| 970 | var one: u16 = 1; | 971 | var one: u16 = 1; |
| 971 | try testing.expect(intToEnum(E1, zero) catch unreachable == E1.A); | 972 | try testing.expect(intToEnum(E1, zero) catch unreachable == E1.A); |
| 972 | try testing.expect(intToEnum(E2, one) catch unreachable == E2.B); | 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 | try testing.expectError(error.InvalidEnumTag, intToEnum(E1, one)); | 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 | pub const IntToEnumError = error{InvalidEnumTag}; | 982 | pub const IntToEnumError = error{InvalidEnumTag}; |
| 977 | | 983 | |
| 978 | pub fn intToEnum(comptime EnumTag: type, tag_int: anytype) IntToEnumError!EnumTag { | 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 | const this_tag_value = @field(EnumTag, f.name); | 995 | const this_tag_value = @field(EnumTag, f.name); |
| 981 | if (tag_int == @enumToInt(this_tag_value)) { | 996 | if (tag_int == @enumToInt(this_tag_value)) { |
| 982 | return this_tag_value; | 997 | return this_tag_value; |