authorgravatar for nekogirl@noreply.codeberg.orgnekogirl <nekogirl@noreply.codeberg.org> 2026-05-17 23:30:36+03:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-06-06 20:41:09-07:00
log4140c9a2c7f5caa626ba0246d5a0905e45ddb12d
tree220cd8946baf214298dac1fcadd8feef2bc00124
parentf78c56aa7de3f70be1d7c9a54fad4803f10f65af

std.meta: remove stringToEnum slow-path


1 files changed, 4 insertions(+), 21 deletions(-)

lib/std/meta.zig+4-21
......@@ -14,31 +14,14 @@ test {
1414 _ = TrailerFlags;
1515}
1616
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.
1819pub 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);
3521}
3622
3723test stringToEnum {
38 const E1 = enum {
39 A,
40 B,
41 };
24 const E1 = enum { A, B };
4225 try testing.expect(E1.A == stringToEnum(E1, "A").?);
4326 try testing.expect(E1.B == stringToEnum(E1, "B").?);
4427 try testing.expect(null == stringToEnum(E1, "C"));