| ... | @@ -483,3 +483,32 @@ test "std.meta.eql" { | ... | @@ -483,3 +483,32 @@ test "std.meta.eql" { |
| 483 | debug.assert(eql(EU.tst(false), EU.tst(false))); | 483 | debug.assert(eql(EU.tst(false), EU.tst(false))); |
| 484 | debug.assert(!eql(EU.tst(false), EU.tst(true))); | 484 | debug.assert(!eql(EU.tst(false), EU.tst(true))); |
| 485 | } | 485 | } |
| | 486 | |
| | 487 | test "intToEnum with error return" { |
| | 488 | const E1 = enum { |
| | 489 | A, |
| | 490 | }; |
| | 491 | const E2 = enum { |
| | 492 | A, |
| | 493 | B, |
| | 494 | }; |
| | 495 | |
| | 496 | var zero: u8 = 0; |
| | 497 | var one: u16 = 1; |
| | 498 | debug.assert(intToEnum(E1, zero) catch unreachable == E1.A); |
| | 499 | debug.assert(intToEnum(E2, one) catch unreachable == E2.B); |
| | 500 | debug.assertError(intToEnum(E1, one), error.InvalidEnumTag); |
| | 501 | } |
| | 502 | |
| | 503 | pub const IntToEnumError = error{InvalidEnumTag}; |
| | 504 | |
| | 505 | pub fn intToEnum(comptime Tag: type, tag_int: var) IntToEnumError!Tag { |
| | 506 | comptime var i = 0; |
| | 507 | inline while (i != @memberCount(Tag)) : (i += 1) { |
| | 508 | const this_tag_value = @field(Tag, @memberName(Tag, i)); |
| | 509 | if (tag_int == @enumToInt(this_tag_value)) { |
| | 510 | return this_tag_value; |
| | 511 | } |
| | 512 | } |
| | 513 | return error.InvalidEnumTag; |
| | 514 | } |