| ... | ... | @@ -303,6 +303,25 @@ test "math.max" { |
| 303 | 303 | testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2); |
| 304 | 304 | } |
| 305 | 305 | |
| 306 | pub 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 | } |
| 311 | test "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 | |
| 306 | 325 | pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) { |
| 307 | 326 | var answer: T = undefined; |
| 308 | 327 | return if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer; |