| ... | @@ -313,10 +313,9 @@ test "math.max" { | ... | @@ -313,10 +313,9 @@ test "math.max" { |
| 313 | testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2); | 313 | testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2); |
| 314 | } | 314 | } |
| 315 | | 315 | |
| 316 | pub fn clamp(clamped_val: var, bound_1: var, bound_2: var) Min(@TypeOf(bound_1), @TypeOf(bound_2)) { | 316 | pub fn clamp(val: var, lower: var, upper: var) @TypeOf(val, lower, upper) { |
| 317 | const upper_bound = max(bound_1, bound_2); | 317 | assert(lower <= upper); |
| 318 | const lower_bound = min(bound_1, bound_2); | 318 | return max(lower, min(val, upper)); |
| 319 | return min(upper_bound, max(clamped_val, lower_bound)); | | |
| 320 | } | 319 | } |
| 321 | test "math.clamp" { | 320 | test "math.clamp" { |
| 322 | // Within range | 321 | // Within range |
| ... | @@ -326,10 +325,13 @@ test "math.clamp" { | ... | @@ -326,10 +325,13 @@ test "math.clamp" { |
| 326 | // Above | 325 | // Above |
| 327 | testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7); | 326 | testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7); |
| 328 | | 327 | |
| 329 | // Reverse | 328 | // Floating point |
| 330 | testing.expect(std.math.clamp(@as(i32, -1), @as(i32, 7), @as(i32, -4)) == -1); | 329 | testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0); |
| 331 | testing.expect(std.math.clamp(@as(i32, -5), @as(i32, 7), @as(i32, -4)) == -4); | 330 | testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5); |
| 332 | testing.expect(std.math.clamp(@as(i32, 8), @as(i32, 7), @as(i32, -4)) == 7); | 331 | |
| | 332 | // Mix of comptime and non-comptime |
| | 333 | var i: i32 = 1; |
| | 334 | testing.expect(std.math.clamp(i, 0, 1) == 1); |
| 333 | } | 335 | } |
| 334 | | 336 | |
| 335 | pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) { | 337 | pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) { |