diff options
| author | Andrew Kelley <andrew@ziglang.org> | 2021-04-24 10:44:41 -0700 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2021-04-24 10:44:41 -0700 |
| commit | e86cee258cb0eefca14a94f6b3abb39e8a5f2ef9 (patch) | |
| tree | 6d9aa3b21685b1581787246f953db94cdb486693 /lib/std/meta.zig | |
| parent | 224fbb23c44628b215662c6199dff11cc2851f04 (diff) | |
| parent | 8530b6b7242ebf43b5cb4ae3a2644593f4961a5e (diff) | |
| download | zig-e86cee258cb0eefca14a94f6b3abb39e8a5f2ef9.tar.gz zig-e86cee258cb0eefca14a94f6b3abb39e8a5f2ef9.zip | |
Merge remote-tracking branch 'origin/master' into stage2-whole-file-astgen
In particular I wanted the change that makes `suspend;` illegal in the
parser.
Diffstat (limited to 'lib/std/meta.zig')
| -rw-r--r-- | lib/std/meta.zig | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/lib/std/meta.zig b/lib/std/meta.zig index a67e04431a..83ef3f83e0 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -884,7 +884,7 @@ pub fn Vector(comptime len: u32, comptime child: type) type { /// Given a type and value, cast the value to the type as c would. /// This is for translate-c and is not intended for general use. pub fn cast(comptime DestType: type, target: anytype) DestType { - // this function should behave like transCCast in translate-c, except it's for macros + // this function should behave like transCCast in translate-c, except it's for macros and enums const SourceType = @TypeOf(target); switch (@typeInfo(DestType)) { .Pointer => { @@ -921,9 +921,10 @@ pub fn cast(comptime DestType: type, target: anytype) DestType { } } }, - .Enum => { + .Enum => |enum_type| { if (@typeInfo(SourceType) == .Int or @typeInfo(SourceType) == .ComptimeInt) { - return @intToEnum(DestType, target); + const intermediate = cast(enum_type.tag_type, target); + return @intToEnum(DestType, intermediate); } }, .Int => { @@ -1011,6 +1012,17 @@ test "std.meta.cast" { testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*volatile u8, 2))); testing.expectEqual(@intToPtr(?*c_void, 2), cast(?*c_void, @intToPtr(*u8, 2))); + + const C_ENUM = extern enum(c_int) { + A = 0, + B, + C, + _, + }; + testing.expectEqual(cast(C_ENUM, @as(i64, -1)), @intToEnum(C_ENUM, -1)); + testing.expectEqual(cast(C_ENUM, @as(i8, 1)), .B); + testing.expectEqual(cast(C_ENUM, @as(u64, 1)), .B); + testing.expectEqual(cast(C_ENUM, @as(u64, 42)), @intToEnum(C_ENUM, 42)); } /// Given a value returns its size as C's sizeof operator would. |
