zig

fork of https://codeberg.org/ziglang/zig
Log | Tree | Refs | README | LICENSE

commit f6cd02be6551f3ca702b76b7ca2ab7567effe680 (tree)
parent a07490a4bc501334727e70b9dca387d03c24fe2e
Author: daurnimator <quae@daurnimator.com>
Date:   Mon, 26 Nov 2018 02:08:12 +1100

add std.meta.stringToEnum

Diffstat:
Mstd/meta/index.zig | 19+++++++++++++++++++
1 file changed, 19 insertions(+), 0 deletions(-)

diff --git a/std/meta/index.zig b/std/meta/index.zig @@ -76,6 +76,25 @@ test "std.meta.tagName" { debug.assert(mem.eql(u8, tagName(u2b), "D")); } +pub fn stringToEnum(comptime T: type, str: []const u8) ?T { + inline for (@typeInfo(T).Enum.fields) |enumField| { + if (std.mem.eql(u8, str, enumField.name)) { + return @field(T, enumField.name); + } + } + return null; +} + +test "std.meta.stringToEnum" { + const E1 = enum { + A, + B, + }; + debug.assert(E1.A == stringToEnum(E1, "A").?); + debug.assert(E1.B == stringToEnum(E1, "B").?); + debug.assert(null == stringToEnum(E1, "C")); +} + pub fn bitCount(comptime T: type) u32 { return switch (@typeInfo(T)) { TypeId.Int => |info| info.bits,