authorgravatar for hershkrishna@protonmail.chHersh Krishna <hershkrishna@protonmail.ch> 2020-01-13 19:08:43-06:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-01-14 13:06:46-05:00
loge7917d099d5a654926ffbd352e149c9d45a196b1
tree43c882a5b44299d815215bd3c209a1341cf618d1
parentd3e67d99216d3dd6c18259c17652fcad54aebc21

Add clamp function to math module


1 files changed, 19 insertions(+), 0 deletions(-)

lib/std/math.zig+19
......@@ -303,6 +303,25 @@ test "math.max" {
303303 testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
304304}
305305
306pub fn clamp(clamped_val: var, bound_1: var, bound_2: var) Min(@TypeOf(bound_1), @TypeOf(bound_2)) {
307 const upper_bound = max(bound_1, bound_2);
308 const lower_bound = min(bound_1, bound_2);
309 return min(upper_bound, max(clamped_val, lower_bound));
310}
311test "math.clamp" {
312 // Within range
313 testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
314 // Below
315 testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4);
316 // Above
317 testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
318
319 // Reverse
320 testing.expect(std.math.clamp(@as(i32, -1), @as(i32, 7), @as(i32, -4)) == -1);
321 testing.expect(std.math.clamp(@as(i32, -5), @as(i32, 7), @as(i32, -4)) == -4);
322 testing.expect(std.math.clamp(@as(i32, 8), @as(i32, 7), @as(i32, -4)) == 7);
323}
324
306325pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
307326 var answer: T = undefined;
308327 return if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer;