aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorAndrius Mitkus <andrius.mitkus@gmail.com>2020-04-16 22:12:00 +0300
committerAndrew Kelley <andrew@ziglang.org>2020-04-16 16:19:12 -0400
commit157f566f2dd9c8d694270f5b7fcb8525834d7646 (patch)
tree3eb6a423433195fc99910f6b20698f0646b47830 /lib
parent480deacbab9c86d3cff32e59665e9f70b45e453d (diff)
downloadzig-157f566f2dd9c8d694270f5b7fcb8525834d7646.tar.gz
zig-157f566f2dd9c8d694270f5b7fcb8525834d7646.zip
std: make math.clamp work for common uses, remove automatic bounds swapping
Diffstat (limited to 'lib')
-rw-r--r--lib/std/math.zig18
1 files changed, 10 insertions, 8 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig
index df1a522046..e6dfc53235 100644
--- a/lib/std/math.zig
+++ b/lib/std/math.zig
@@ -313,10 +313,9 @@ test "math.max" {
testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
}
-pub fn clamp(clamped_val: var, bound_1: var, bound_2: var) Min(@TypeOf(bound_1), @TypeOf(bound_2)) {
- const upper_bound = max(bound_1, bound_2);
- const lower_bound = min(bound_1, bound_2);
- return min(upper_bound, max(clamped_val, lower_bound));
+pub fn clamp(val: var, lower: var, upper: var) @TypeOf(val, lower, upper) {
+ assert(lower <= upper);
+ return max(lower, min(val, upper));
}
test "math.clamp" {
// Within range
@@ -326,10 +325,13 @@ test "math.clamp" {
// Above
testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
- // Reverse
- testing.expect(std.math.clamp(@as(i32, -1), @as(i32, 7), @as(i32, -4)) == -1);
- testing.expect(std.math.clamp(@as(i32, -5), @as(i32, 7), @as(i32, -4)) == -4);
- testing.expect(std.math.clamp(@as(i32, 8), @as(i32, 7), @as(i32, -4)) == 7);
+ // Floating point
+ testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
+ testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
+
+ // Mix of comptime and non-comptime
+ var i: i32 = 1;
+ testing.expect(std.math.clamp(i, 0, 1) == 1);
}
pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {