authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2022-09-20 22:46:42-04:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2022-10-11 19:51:03-04:00
log7a89eebfc64fd81a504700e105bdc2609bb2a442
tree133017cd1927707e78cec899399f3c9b6ef3cd58
parente6ebdcb82ed9fd226ef18670115b8b2617c0a392

std.math: add support to cast for a comptime_int argument

This allows converting a comptime_int to an optional integer type, which either behaves the same as an implicit cast or produces null if the argument is outside the range of the destination type.

1 files changed, 10 insertions(+), 3 deletions(-)

lib/std/math.zig+10-3
...@@ -1062,10 +1062,11 @@ test "negateCast" {...@@ -1062,10 +1062,11 @@ test "negateCast" {
1062/// return null.1062/// return null.
1063pub fn cast(comptime T: type, x: anytype) ?T {1063pub fn cast(comptime T: type, x: anytype) ?T {
1064 comptime assert(@typeInfo(T) == .Int); // must pass an integer1064 comptime assert(@typeInfo(T) == .Int); // must pass an integer
1065 comptime assert(@typeInfo(@TypeOf(x)) == .Int); // must pass an integer1065 const is_comptime = @TypeOf(x) == comptime_int;
1066 if (maxInt(@TypeOf(x)) > maxInt(T) and x > maxInt(T)) {1066 comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .Int); // must pass an integer
1067 if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) {
1067 return null;1068 return null;
1068 } else if (minInt(@TypeOf(x)) < minInt(T) and x < minInt(T)) {1069 } else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) {
1069 return null;1070 return null;
1070 } else {1071 } else {
1071 return @intCast(T, x);1072 return @intCast(T, x);
...@@ -1073,12 +1074,18 @@ pub fn cast(comptime T: type, x: anytype) ?T {...@@ -1073,12 +1074,18 @@ pub fn cast(comptime T: type, x: anytype) ?T {
1073}1074}
10741075
1075test "cast" {1076test "cast" {
1077 try testing.expect(cast(u8, 300) == null);
1076 try testing.expect(cast(u8, @as(u32, 300)) == null);1078 try testing.expect(cast(u8, @as(u32, 300)) == null);
1079 try testing.expect(cast(i8, -200) == null);
1077 try testing.expect(cast(i8, @as(i32, -200)) == null);1080 try testing.expect(cast(i8, @as(i32, -200)) == null);
1081 try testing.expect(cast(u8, -1) == null);
1078 try testing.expect(cast(u8, @as(i8, -1)) == null);1082 try testing.expect(cast(u8, @as(i8, -1)) == null);
1083 try testing.expect(cast(u64, -1) == null);
1079 try testing.expect(cast(u64, @as(i8, -1)) == null);1084 try testing.expect(cast(u64, @as(i8, -1)) == null);
10801085
1086 try testing.expect(cast(u8, 255).? == @as(u8, 255));
1081 try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255));1087 try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255));
1088 try testing.expect(@TypeOf(cast(u8, 255).?) == u8);
1082 try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8);1089 try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8);
1083}1090}
10841091