authorgravatar for koend@tuta.iokoenditor <koend@tuta.io> 2024-06-01 08:21:48+03:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2024-06-01 13:28:16+03:00
log64ef45eb059328ac8579c22506fa7574e8cf45f2
treed7b554a90fc86a0344b714a91e720528025b1788
parente09963d8544c19812db20e520f09f6e5d9a57d64

Support Vectors in std.math.clamp


1 files changed, 12 insertions(+), 1 deletions(-)

lib/std/math.zig+12-1
...@@ -518,7 +518,15 @@ test wrap {...@@ -518,7 +518,15 @@ test wrap {
518/// ```518/// ```
519/// Limit val to the inclusive range [lower, upper].519/// Limit val to the inclusive range [lower, upper].
520pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {520pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
521 assert(lower <= upper);521 const T = @TypeOf(val, lower, upper);
522 switch (@typeInfo(T)) {
523 .Int, .Float, .ComptimeInt, .ComptimeFloat => assert(lower <= upper),
524 .Vector => |vinfo| switch (@typeInfo(vinfo.child)) {
525 .Int, .Float => assert(@reduce(.And, lower <= upper)),
526 else => @compileError("Expected vector of ints or floats, found " ++ @typeName(T)),
527 },
528 else => @compileError("Expected an int, float or vector of one, found " ++ @typeName(T)),
529 }
522 return @max(lower, @min(val, upper));530 return @max(lower, @min(val, upper));
523}531}
524test clamp {532test clamp {
...@@ -533,6 +541,9 @@ test clamp {...@@ -533,6 +541,9 @@ test clamp {
533 try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);541 try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
534 try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);542 try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
535543
544 // Vector
545 try testing.expect(@reduce(.And, std.math.clamp(@as(@Vector(3, f32), .{ 1.4, 15.23, 28.3 }), @as(@Vector(3, f32), .{ 9.8, 13.2, 15.6 }), @as(@Vector(3, f32), .{ 15.2, 22.8, 26.3 })) == @as(@Vector(3, f32), .{ 9.8, 15.23, 26.3 })));
546
536 // Mix of comptime and non-comptime547 // Mix of comptime and non-comptime
537 var i: i32 = 1;548 var i: i32 = 1;
538 _ = &i;549 _ = &i;