| ... | @@ -16,53 +16,7 @@ test { | ... | @@ -16,53 +16,7 @@ test { |
| 16 | | 16 | |
| 17 | pub const tagName = @compileError("deprecated; use @tagName or @errorName directly"); | 17 | pub const tagName = @compileError("deprecated; use @tagName or @errorName directly"); |
| 18 | | 18 | |
| 19 | /// Given an enum or tagged union, returns true if the comptime-supplied | 19 | pub const isTag = @compileError("deprecated; use 'tagged_value == @field(E, tag_name)' directly"); |
| 20 | /// string matches the name of the tag value. This match process should | | |
| 21 | /// be, at runtime, O(1) in the number of tags available to the enum or | | |
| 22 | /// union, and it should also be O(1) in the length of the comptime tag | | |
| 23 | /// names. | | |
| 24 | pub fn isTag(tagged_value: anytype, comptime tag_name: []const u8) bool { | | |
| 25 | const T = @TypeOf(tagged_value); | | |
| 26 | const type_info = @typeInfo(T); | | |
| 27 | const type_name = @typeName(T); | | |
| 28 | | | |
| 29 | // select the Enum type out of the type (in the case of the tagged union, extract it) | | |
| 30 | const E = if (.Enum == type_info) T else if (.Union == type_info) (type_info.Union.tag_type orelse { | | |
| 31 | @compileError("attempted to use isTag on the untagged union " ++ type_name); | | |
| 32 | }) else { | | |
| 33 | @compileError("attempted to use isTag on a value of type (" ++ type_name ++ ") that isn't an enum or a union."); | | |
| 34 | }; | | |
| 35 | | | |
| 36 | return tagged_value == @field(E, tag_name); | | |
| 37 | } | | |
| 38 | | | |
| 39 | test "std.meta.isTag for Enums" { | | |
| 40 | const EnumType = enum { a, b }; | | |
| 41 | var a_type: EnumType = .a; | | |
| 42 | var b_type: EnumType = .b; | | |
| 43 | | | |
| 44 | try testing.expect(isTag(a_type, "a")); | | |
| 45 | try testing.expect(!isTag(a_type, "b")); | | |
| 46 | try testing.expect(isTag(b_type, "b")); | | |
| 47 | try testing.expect(!isTag(b_type, "a")); | | |
| 48 | } | | |
| 49 | | | |
| 50 | test "std.meta.isTag for Tagged Unions" { | | |
| 51 | const TaggedUnionEnum = enum { int, flt }; | | |
| 52 | | | |
| 53 | const TaggedUnionType = union(TaggedUnionEnum) { | | |
| 54 | int: i64, | | |
| 55 | flt: f64, | | |
| 56 | }; | | |
| 57 | | | |
| 58 | var int = TaggedUnionType{ .int = 1234 }; | | |
| 59 | var flt = TaggedUnionType{ .flt = 12.34 }; | | |
| 60 | | | |
| 61 | try testing.expect(isTag(int, "int")); | | |
| 62 | try testing.expect(!isTag(int, "flt")); | | |
| 63 | try testing.expect(isTag(flt, "flt")); | | |
| 64 | try testing.expect(!isTag(flt, "int")); | | |
| 65 | } | | |
| 66 | | 20 | |
| 67 | /// Returns the variant of an enum type, `T`, which is named `str`, or `null` if no such variant exists. | 21 | /// Returns the variant of an enum type, `T`, which is named `str`, or `null` if no such variant exists. |
| 68 | pub fn stringToEnum(comptime T: type, str: []const u8) ?T { | 22 | pub fn stringToEnum(comptime T: type, str: []const u8) ?T { |