authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2018-11-26 02:08:12+11:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-11-25 11:48:11-05:00
logf6cd02be6551f3ca702b76b7ca2ab7567effe680
treeb691de55d6cadd85219df7c8035eb237c0f65a1a
parenta07490a4bc501334727e70b9dca387d03c24fe2e

add std.meta.stringToEnum


1 files changed, 19 insertions(+), 0 deletions(-)

std/meta/index.zig+19
...@@ -76,6 +76,25 @@ test "std.meta.tagName" {...@@ -76,6 +76,25 @@ test "std.meta.tagName" {
76 debug.assert(mem.eql(u8, tagName(u2b), "D"));76 debug.assert(mem.eql(u8, tagName(u2b), "D"));
77}77}
7878
79pub fn stringToEnum(comptime T: type, str: []const u8) ?T {
80 inline for (@typeInfo(T).Enum.fields) |enumField| {
81 if (std.mem.eql(u8, str, enumField.name)) {
82 return @field(T, enumField.name);
83 }
84 }
85 return null;
86}
87
88test "std.meta.stringToEnum" {
89 const E1 = enum {
90 A,
91 B,
92 };
93 debug.assert(E1.A == stringToEnum(E1, "A").?);
94 debug.assert(E1.B == stringToEnum(E1, "B").?);
95 debug.assert(null == stringToEnum(E1, "C"));
96}
97
79pub fn bitCount(comptime T: type) u32 {98pub fn bitCount(comptime T: type) u32 {
80 return switch (@typeInfo(T)) {99 return switch (@typeInfo(T)) {
81 TypeId.Int => |info| info.bits,100 TypeId.Int => |info| info.bits,