aboutsummaryrefslogtreecommitdiff
path: root/std/math
diff options
context:
space:
mode:
authorAndrew Kelley <superjoe30@gmail.com>2018-04-04 17:22:26 -0400
committerAndrew Kelley <superjoe30@gmail.com>2018-04-04 17:22:26 -0400
commitcca93908e6d57f18054d153ca01d6869739306f2 (patch)
treeb7316e13386963e5b08aebc1f5707498b64a9ebb /std/math
parentc541ac240c3ad17dda964f9de085a5e8f5472c7a (diff)
parent8938429ea12ff2857ace5380932a7cd68d3b4ab1 (diff)
downloadzig-cca93908e6d57f18054d153ca01d6869739306f2.tar.gz
zig-cca93908e6d57f18054d153ca01d6869739306f2.zip
Merge remote-tracking branch 'origin/master' into llvm7
Diffstat (limited to 'std/math')
-rw-r--r--std/math/index.zig17
1 files changed, 15 insertions, 2 deletions
diff --git a/std/math/index.zig b/std/math/index.zig
index f8668cc00d..477dafcbcc 100644
--- a/std/math/index.zig
+++ b/std/math/index.zig
@@ -515,15 +515,28 @@ test "math.negateCast" {
/// Cast an integer to a different integer type. If the value doesn't fit,
/// return an error.
-pub fn cast(comptime T: type, x: var) !T {
+pub fn cast(comptime T: type, x: var) (error{Overflow}!T) {
comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer
- if (x > @maxValue(T)) {
+ comptime assert(@typeId(@typeOf(x)) == builtin.TypeId.Int); // must pass an integer
+ if (@maxValue(@typeOf(x)) > @maxValue(T) and x > @maxValue(T)) {
+ return error.Overflow;
+ } else if (@minValue(@typeOf(x)) < @minValue(T) and x < @minValue(T)) {
return error.Overflow;
} else {
return T(x);
}
}
+test "math.cast" {
+ if (cast(u8, u32(300))) |_| @panic("fail") else |err| assert(err == error.Overflow);
+ if (cast(i8, i32(-200))) |_| @panic("fail") else |err| assert(err == error.Overflow);
+ if (cast(u8, i8(-1))) |_| @panic("fail") else |err| assert(err == error.Overflow);
+ if (cast(u64, i8(-1))) |_| @panic("fail") else |err| assert(err == error.Overflow);
+
+ assert((try cast(u8, u32(255))) == u8(255));
+ assert(@typeOf(try cast(u8, u32(255))) == u8);
+}
+
pub fn floorPowerOfTwo(comptime T: type, value: T) T {
var x = value;