| ... | ... | @@ -14,31 +14,14 @@ test { |
| 14 | 14 | _ = TrailerFlags; |
| 15 | 15 | } |
| 16 | 16 | |
| 17 | | /// Returns the variant of an enum type, `T`, which is named `str`, or `null` if no such variant exists. |
| 17 | /// Returns the variant of an enum type corresponding to the provided tag name, |
| 18 | /// or `null` if no such variant exists. |
| 18 | 19 | pub fn stringToEnum(comptime T: type, tag_name: []const u8) ?T { |
| 19 | | // Using StaticStringMap here is more performant, but it will start to take too |
| 20 | | // long to compile if the enum is large enough, due to the current limits of comptime |
| 21 | | // performance when doing things like constructing lookup maps at comptime. |
| 22 | | // TODO The '100' here is arbitrary and should be increased when possible: |
| 23 | | // - https://github.com/ziglang/zig/issues/4055 |
| 24 | | // - https://github.com/ziglang/zig/issues/3863 |
| 25 | | if (@typeInfo(T).@"enum".field_names.len <= 100) { |
| 26 | | return std.StaticStringMap(T).initEnum().get(tag_name); |
| 27 | | } else { |
| 28 | | inline for (@typeInfo(T).@"enum".field_names) |name| { |
| 29 | | if (mem.eql(u8, tag_name, name)) { |
| 30 | | return @field(T, name); |
| 31 | | } |
| 32 | | } |
| 33 | | return null; |
| 34 | | } |
| 20 | return std.StaticStringMap(T).initEnum().get(tag_name); |
| 35 | 21 | } |
| 36 | 22 | |
| 37 | 23 | test stringToEnum { |
| 38 | | const E1 = enum { |
| 39 | | A, |
| 40 | | B, |
| 41 | | }; |
| 24 | const E1 = enum { A, B }; |
| 42 | 25 | try testing.expect(E1.A == stringToEnum(E1, "A").?); |
| 43 | 26 | try testing.expect(E1.B == stringToEnum(E1, "B").?); |
| 44 | 27 | try testing.expect(null == stringToEnum(E1, "C")); |