From dd38cb5e89a951af5f298d69297ac2828fc85650 Mon Sep 17 00:00:00 2001 From: lmp Date: Sat, 10 Feb 2024 20:30:05 +0100 Subject: [PATCH] math: add `clamp/3` to clamp numbers in a range --- mth/math.v | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mth/math.v b/mth/math.v index b0732b8..377b0f1 100644 --- a/mth/math.v +++ b/mth/math.v @@ -44,6 +44,12 @@ pub fn gcd[T](a T, b T) T { }) } +// clamp clamps `num` to be between `min` and `max`. +@[inline] +pub fn clamp[T](num T, min_in_range T, max_in_range T) T { + return max[T](min_in_range, min[T](max_in_range, num)) +} + // reduce reduces a fraction by finding the Greatest Common Divisor and dividing by it. pub fn reduce_fraction[T](numerator T, denominator T) (T, T) { g_c_d := gcd(numerator, denominator)