diff options
| author | Andrea Orru <andrea@orru.io> | 2018-04-11 00:33:19 -0700 |
|---|---|---|
| committer | Andrea Orru <andrea@orru.io> | 2018-04-11 00:33:19 -0700 |
| commit | 135a335ce12a33666e44cb13e0be4bb893877565 (patch) | |
| tree | 23b10bed3d36e3fb244c6a2e5d5765d8b7a71fb5 /std/math | |
| parent | b01c5a95c468650f143e0ae96f6c3865852fdcda (diff) | |
| parent | f43711e5fbbedafa1c28c933fdca0949427c77cd (diff) | |
| download | zig-135a335ce12a33666e44cb13e0be4bb893877565.tar.gz zig-135a335ce12a33666e44cb13e0be4bb893877565.zip | |
Merge branch 'master' into zen_stdlib
Diffstat (limited to 'std/math')
| -rw-r--r-- | std/math/atan2.zig | 2 | ||||
| -rw-r--r-- | std/math/index.zig | 17 |
2 files changed, 16 insertions, 3 deletions
diff --git a/std/math/atan2.zig b/std/math/atan2.zig index 6f29b7b18d..37c520da46 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -22,7 +22,7 @@ const std = @import("../index.zig"); const math = std.math; const assert = std.debug.assert; -fn atan2(comptime T: type, x: T, y: T) T { +pub fn atan2(comptime T: type, x: T, y: T) T { return switch (T) { f32 => atan2_32(x, y), f64 => atan2_64(x, y), 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; |
