aboutsummaryrefslogtreecommitdiff
path: root/lib/std/meta.zig
diff options
context:
space:
mode:
authorwooster0 <wooster0@proton.me>2025-05-11 17:38:16 +0900
committerAlex Rønne Petersen <alex@alexrp.com>2025-05-13 07:28:41 +0200
commita365971a337116dd23df2b1bc86468d54885b4b2 (patch)
tree070dfe739796151d4d1256a3cedd83989609be42 /lib/std/meta.zig
parenta3693aae3a9417c4298788af570762945b21ccba (diff)
downloadzig-a365971a337116dd23df2b1bc86468d54885b4b2.tar.gz
zig-a365971a337116dd23df2b1bc86468d54885b4b2.zip
std.meta.intToEnum -> std.enums.fromInt
Also use an optional as the return type instead of an error code.
Diffstat (limited to 'lib/std/meta.zig')
-rw-r--r--lib/std/meta.zig52
1 files changed, 3 insertions, 49 deletions
diff --git a/lib/std/meta.zig b/lib/std/meta.zig
index c0aef1fb51..5707527aed 100644
--- a/lib/std/meta.zig
+++ b/lib/std/meta.zig
@@ -857,58 +857,12 @@ test eql {
try testing.expect(!eql(CU{ .a = {} }, .b));
}
-test intToEnum {
- const E1 = enum {
- A,
- };
- const E2 = enum {
- A,
- B,
- };
- const E3 = enum(i8) { A, _ };
-
- var zero: u8 = 0;
- var one: u16 = 1;
- _ = &zero;
- _ = &one;
- try testing.expect(intToEnum(E1, zero) catch unreachable == E1.A);
- try testing.expect(intToEnum(E2, one) catch unreachable == E2.B);
- try testing.expect(intToEnum(E3, zero) catch unreachable == E3.A);
- try testing.expect(intToEnum(E3, 127) catch unreachable == @as(E3, @enumFromInt(127)));
- try testing.expect(intToEnum(E3, -128) catch unreachable == @as(E3, @enumFromInt(-128)));
- try testing.expectError(error.InvalidEnumTag, intToEnum(E1, one));
- try testing.expectError(error.InvalidEnumTag, intToEnum(E3, 128));
- try testing.expectError(error.InvalidEnumTag, intToEnum(E3, -129));
-}
-
+/// Deprecated: use `std.enums.fromInt` instead and handle null.
pub const IntToEnumError = error{InvalidEnumTag};
+/// Deprecated: use `std.enums.fromInt` instead and handle null instead of an error.
pub fn intToEnum(comptime EnumTag: type, tag_int: anytype) IntToEnumError!EnumTag {
- const enum_info = @typeInfo(EnumTag).@"enum";
-
- if (!enum_info.is_exhaustive) {
- if (std.math.cast(enum_info.tag_type, tag_int)) |tag| {
- return @as(EnumTag, @enumFromInt(tag));
- }
- return error.InvalidEnumTag;
- }
-
- // We don't directly iterate over the fields of EnumTag, as that
- // would require an inline loop. Instead, we create an array of
- // values that is comptime-know, but can be iterated at runtime
- // without requiring an inline loop. This generates better
- // machine code.
- const values = comptime blk: {
- var result: [enum_info.fields.len]enum_info.tag_type = undefined;
- for (&result, enum_info.fields) |*dst, src| {
- dst.* = src.value;
- }
- break :blk result;
- };
- for (values) |v| {
- if (v == tag_int) return @enumFromInt(tag_int);
- }
- return error.InvalidEnumTag;
+ return std.enums.fromInt(EnumTag, tag_int) orelse return error.InvalidEnumTag;
}
/// Given a type and a name, return the field index according to source order.