diff options
| author | Jacob Young <jacobly0@users.noreply.github.com> | 2022-09-20 22:46:42 -0400 |
|---|---|---|
| committer | Jacob Young <jacobly0@users.noreply.github.com> | 2022-10-11 19:51:03 -0400 |
| commit | 7a89eebfc64fd81a504700e105bdc2609bb2a442 (patch) | |
| tree | 133017cd1927707e78cec899399f3c9b6ef3cd58 /lib/std/math.zig | |
| parent | e6ebdcb82ed9fd226ef18670115b8b2617c0a392 (diff) | |
| download | zig-7a89eebfc64fd81a504700e105bdc2609bb2a442.tar.gz zig-7a89eebfc64fd81a504700e105bdc2609bb2a442.zip | |
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.
Diffstat (limited to 'lib/std/math.zig')
| -rw-r--r-- | lib/std/math.zig | 13 |
1 files changed, 10 insertions, 3 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig index 2f16ecb5d8..8abc4fae66 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -1062,10 +1062,11 @@ test "negateCast" { /// return null. pub fn cast(comptime T: type, x: anytype) ?T { comptime assert(@typeInfo(T) == .Int); // must pass an integer - comptime assert(@typeInfo(@TypeOf(x)) == .Int); // must pass an integer - if (maxInt(@TypeOf(x)) > maxInt(T) and x > maxInt(T)) { + const is_comptime = @TypeOf(x) == comptime_int; + comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .Int); // must pass an integer + if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) { return null; - } else if (minInt(@TypeOf(x)) < minInt(T) and x < minInt(T)) { + } else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) { return null; } else { return @intCast(T, x); @@ -1073,12 +1074,18 @@ pub fn cast(comptime T: type, x: anytype) ?T { } test "cast" { + try testing.expect(cast(u8, 300) == null); try testing.expect(cast(u8, @as(u32, 300)) == null); + try testing.expect(cast(i8, -200) == null); try testing.expect(cast(i8, @as(i32, -200)) == null); + try testing.expect(cast(u8, -1) == null); try testing.expect(cast(u8, @as(i8, -1)) == null); + try testing.expect(cast(u64, -1) == null); try testing.expect(cast(u64, @as(i8, -1)) == null); + try testing.expect(cast(u8, 255).? == @as(u8, 255)); try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255)); + try testing.expect(@TypeOf(cast(u8, 255).?) == u8); try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8); } |
