authorgravatar for andrius.mitkus@gmail.comAndrius Mitkus <andrius.mitkus@gmail.com> 2020-04-16 22:12:00+03:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-04-16 16:19:12-04:00
log157f566f2dd9c8d694270f5b7fcb8525834d7646
tree3eb6a423433195fc99910f6b20698f0646b47830
parent480deacbab9c86d3cff32e59665e9f70b45e453d

std: make math.clamp work for common uses, remove automatic bounds swapping


1 files changed, 10 insertions(+), 8 deletions(-)

lib/std/math.zig+10-8
......@@ -313,10 +313,9 @@ test "math.max" {
313313 testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
314314}
315315
316pub fn clamp(clamped_val: var, bound_1: var, bound_2: var) Min(@TypeOf(bound_1), @TypeOf(bound_2)) {
317 const upper_bound = max(bound_1, bound_2);
318 const lower_bound = min(bound_1, bound_2);
319 return min(upper_bound, max(clamped_val, lower_bound));
316pub fn clamp(val: var, lower: var, upper: var) @TypeOf(val, lower, upper) {
317 assert(lower <= upper);
318 return max(lower, min(val, upper));
320319}
321320test "math.clamp" {
322321 // Within range
......@@ -326,10 +325,13 @@ test "math.clamp" {
326325 // Above
327326 testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
328327
329 // Reverse
330 testing.expect(std.math.clamp(@as(i32, -1), @as(i32, 7), @as(i32, -4)) == -1);
331 testing.expect(std.math.clamp(@as(i32, -5), @as(i32, 7), @as(i32, -4)) == -4);
332 testing.expect(std.math.clamp(@as(i32, 8), @as(i32, 7), @as(i32, -4)) == 7);
328 // Floating point
329 testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
330 testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
331
332 // Mix of comptime and non-comptime
333 var i: i32 = 1;
334 testing.expect(std.math.clamp(i, 0, 1) == 1);
333335}
334336
335337pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {