26 lines
833 B
Zig
26 lines
833 B
Zig
const std = @import("std");
|
|
const assert = std.debug.assert;
|
|
|
|
// TODO: use `EnumFieldStruct` for `str_to_tag_mapping`
|
|
pub fn EnumStringUtils(comptime TargetEnum: type, str_to_tag_mapping: anytype) type {
|
|
if (str_to_tag_mapping.len != @typeInfo(TargetEnum).Enum.fields.len) {
|
|
@compileLog("Mapping is not exhaustive");
|
|
}
|
|
|
|
return struct {
|
|
pub fn fromString(str: []const u8) ?TargetEnum {
|
|
const EnumMapping = std.StaticStringMap(TargetEnum).initComptime(str_to_tag_mapping);
|
|
return EnumMapping.get(str);
|
|
}
|
|
|
|
pub fn toString(value: TargetEnum) []const u8 {
|
|
inline for (str_to_tag_mapping) |mapping| {
|
|
if (mapping[1] == value) {
|
|
return mapping[0];
|
|
}
|
|
}
|
|
unreachable;
|
|
}
|
|
};
|
|
}
|