commit 3af842f0e89125e65a87e5752234bf7e0051aa12 (tree)
parent b346090ed273f4ff20873b673e65394c96f4d881
Author: Mason Remaley <mason@anthropicstudios.com>
Date: Mon, 8 Dec 2025 17:24:17 -0800
Fixes enums.fromInt failing at compile time on in range but invalid values
Diffstat:
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/lib/std/enums.zig b/lib/std/enums.zig
@@ -22,7 +22,7 @@ pub fn fromInt(comptime E: type, integer: anytype) ?E {
// without requiring an inline loop.
// This generates better machine code.
for (values(E)) |value| {
- if (@intFromEnum(value) == integer) return @enumFromInt(integer);
+ if (@intFromEnum(value) == integer) return value;
}
return null;
}
@@ -213,6 +213,7 @@ test fromInt {
B,
};
const E3 = enum(i8) { A, _ };
+ const E4 = enum(u8) { A };
var zero: u8 = 0;
var one: u16 = 1;
@@ -226,6 +227,10 @@ test fromInt {
try testing.expectEqual(null, fromInt(E1, one));
try testing.expectEqual(null, fromInt(E3, 128));
try testing.expectEqual(null, fromInt(E3, -129));
+
+ // `fromInt` used to produce a compiler error instead of `null` if trying to convert an integer
+ // that wasn't out of range, but also wasn't a valid value.
+ try testing.expectEqual(null, fromInt(E4, 1));
}
/// A set of enum elements, backed by a bitfield. If the enum