Function stringToEnum [src]
Returns the variant of an enum type, T, which is named str, or null if no such variant exists.
Prototype
pub fn stringToEnum(comptime T: type, str: []const u8) ?T
Parameters
T: type
str: []const u8
Example
test stringToEnum {
const E1 = enum {
A,
B,
};
try testing.expect(E1.A == stringToEnum(E1, "A").?);
try testing.expect(E1.B == stringToEnum(E1, "B").?);
try testing.expect(null == stringToEnum(E1, "C"));
}
Source
pub fn stringToEnum(comptime T: type, str: []const u8) ?T {
// Using StaticStringMap here is more performant, but it will start to take too
// long to compile if the enum is large enough, due to the current limits of comptime
// performance when doing things like constructing lookup maps at comptime.
// TODO The '100' here is arbitrary and should be increased when possible:
// - https://github.com/ziglang/zig/issues/4055
// - https://github.com/ziglang/zig/issues/3863
if (@typeInfo(T).@"enum".fields.len <= 100) {
const kvs = comptime build_kvs: {
const EnumKV = struct { []const u8, T };
var kvs_array: [@typeInfo(T).@"enum".fields.len]EnumKV = undefined;
for (@typeInfo(T).@"enum".fields, 0..) |enumField, i| {
kvs_array[i] = .{ enumField.name, @field(T, enumField.name) };
}
break :build_kvs kvs_array[0..];
};
const map = std.StaticStringMap(T).initComptime(kvs);
return map.get(str);
} else {
inline for (@typeInfo(T).@"enum".fields) |enumField| {
if (mem.eql(u8, str, enumField.name)) {
return @field(T, enumField.name);
}
}
return null;
}
}