aboutsummaryrefslogtreecommitdiff
path: root/builtins
diff options
context:
space:
mode:
authorBruce Hill <bruce@bruce-hill.com>2024-08-18 23:20:54 -0400
committerBruce Hill <bruce@bruce-hill.com>2024-08-18 23:20:54 -0400
commitb76fbd3beba08c098c6d18578230f9edbc4d3a3d (patch)
treec87b3488a3846523f4f56c9685ffafa06fdc771b /builtins
parent0864d82c3f8634f449186f775b0bbcaa872bb43c (diff)
Add Int:clamped() and Num:clamped()
Diffstat (limited to 'builtins')
-rw-r--r--builtins/integers.h8
-rw-r--r--builtins/nums.h6
2 files changed, 14 insertions, 0 deletions
diff --git a/builtins/integers.h b/builtins/integers.h
index ed3e293c..b4cb2113 100644
--- a/builtins/integers.h
+++ b/builtins/integers.h
@@ -34,6 +34,9 @@
c_type type_name ## $random(c_type min, c_type max); \
Range_t type_name ## $to(c_type from, c_type to); \
c_type type_name ## $from_text(CORD text, CORD *the_rest); \
+ static inline c_type type_name ## $clamped(c_type x, c_type min, c_type max) { \
+ return x < min ? min : (x > max ? max : x); \
+ } \
extern const c_type type_name ## $min, type_name##$max; \
extern const TypeInfo $ ## type_name; \
static inline c_type type_name ## $divided_by(c_type D, c_type d) { \
@@ -123,6 +126,11 @@ Int_t Int$prev_prime(Int_t x);
extern const TypeInfo $Int;
+static inline Int_t Int$clamped(Int_t x, Int_t low, Int_t high)
+{
+ return (Int$compare(&x, &low, &$Int) <= 0) ? low : (Int$compare(&x, &high, &$Int) >= 0 ? high : x);
+}
+
// Fast-path inline versions for the common case where integer arithmetic is
// between two small ints.
diff --git a/builtins/nums.h b/builtins/nums.h
index d08dcc44..94b11055 100644
--- a/builtins/nums.h
+++ b/builtins/nums.h
@@ -28,6 +28,9 @@ double Num$nan(CORD tag);
double Num$random(void);
double Num$mix(double amount, double x, double y);
double Num$from_text(CORD text, CORD *the_rest);
+static inline double Num$clamped(double x, double low, double high) {
+ return (x <= low) ? low : (x >= high ? high : x);
+}
extern const TypeInfo $Num;
CORD Num32$as_text(const float *f, bool colorize, const TypeInfo *type);
@@ -44,6 +47,9 @@ float Num32$random(void);
float Num32$mix(float amount, float x, float y);
float Num32$from_text(CORD text, CORD *the_rest);
float Num32$nan(CORD tag);
+static inline float Num32$clamped(float x, float low, float high) {
+ return (x <= low) ? low : (x >= high ? high : x);
+}
extern const TypeInfo $Num32;
// vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0