diff options
| author | Ali Chraghi <chraghiali1@gmail.com> | 2022-05-22 19:36:59 +0430 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2022-05-27 16:43:33 -0400 |
| commit | 0e6285c8fc31ff866df96847fe34e660da38b4a9 (patch) | |
| tree | 5d5830d5b3ce6c13041aacb7e073763551cb4852 /lib/std/math.zig | |
| parent | ddd5b57045d38b7d1f7d5a4120302797433233cd (diff) | |
| download | zig-0e6285c8fc31ff866df96847fe34e660da38b4a9.tar.gz zig-0e6285c8fc31ff866df96847fe34e660da38b4a9.zip | |
math: make `cast` return optional instead of an error
Diffstat (limited to 'lib/std/math.zig')
| -rw-r--r-- | lib/std/math.zig | 21 |
1 files changed, 10 insertions, 11 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig index b936183482..de77663d5b 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -989,28 +989,27 @@ test "negateCast" { } /// Cast an integer to a different integer type. If the value doesn't fit, -/// return an error. -/// TODO make this an optional not an error. -pub fn cast(comptime T: type, x: anytype) (error{Overflow}!T) { +/// 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)) { - return error.Overflow; + return null; } else if (minInt(@TypeOf(x)) < minInt(T) and x < minInt(T)) { - return error.Overflow; + return null; } else { return @intCast(T, x); } } test "cast" { - try testing.expectError(error.Overflow, cast(u8, @as(u32, 300))); - try testing.expectError(error.Overflow, cast(i8, @as(i32, -200))); - try testing.expectError(error.Overflow, cast(u8, @as(i8, -1))); - try testing.expectError(error.Overflow, cast(u64, @as(i8, -1))); + try testing.expect(cast(u8, @as(u32, 300)) == null); + try testing.expect(cast(i8, @as(i32, -200)) == null); + try testing.expect(cast(u8, @as(i8, -1)) == null); + try testing.expect(cast(u64, @as(i8, -1)) == null); - try testing.expect((try cast(u8, @as(u32, 255))) == @as(u8, 255)); - try testing.expect(@TypeOf(try cast(u8, @as(u32, 255))) == u8); + try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255)); + try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8); } pub const AlignCastError = error{UnalignedMemory}; |
