diff options
| author | Hersh Krishna <hershkrishna@protonmail.ch> | 2020-01-13 19:08:43 -0600 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2020-01-14 13:06:46 -0500 |
| commit | e7917d099d5a654926ffbd352e149c9d45a196b1 (patch) | |
| tree | 43c882a5b44299d815215bd3c209a1341cf618d1 /lib/std | |
| parent | d3e67d99216d3dd6c18259c17652fcad54aebc21 (diff) | |
| download | zig-e7917d099d5a654926ffbd352e149c9d45a196b1.tar.gz zig-e7917d099d5a654926ffbd352e149c9d45a196b1.zip | |
Add clamp function to math module
Diffstat (limited to 'lib/std')
| -rw-r--r-- | lib/std/math.zig | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig index 051dc341a2..5885964c34 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -303,6 +303,25 @@ 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)); +} +test "math.clamp" { + // Within range + testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1); + // Below + testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4); + // 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); +} + pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) { var answer: T = undefined; return if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer; |
