Sun, 06 Jul 2025 18:57:43 +0200
make asc_clamp() generic and support all common types
src/ascension/datatypes.h | file | annotate | diff | comparison | revisions |
--- a/src/ascension/datatypes.h Sun Jul 06 18:49:44 2025 +0200 +++ b/src/ascension/datatypes.h Sun Jul 06 18:57:43 2025 +0200 @@ -142,18 +142,51 @@ return true; } -static inline int asc_clamp_i(int v, int min, int max) { +static inline int asc_clampi(int v, int min, int max) { + if (v < min) return min; + if (v > max) return max; + return v; +} + +static inline unsigned asc_clampu(unsigned v, unsigned min, unsigned max) { + if (v < min) return min; + if (v > max) return max; + return v; +} + +static inline long long int asc_clampll(long long int v, long long int min, long long int max) { if (v < min) return min; if (v > max) return max; return v; } -static inline unsigned asc_clamp_u(unsigned v, unsigned min, unsigned max) { +static inline unsigned long long int asc_clampull(unsigned long long int v, unsigned long long int min, unsigned long long int max) { + if (v < min) return min; + if (v > max) return max; + return v; +} + +static inline float asc_clampf(float v, float min, float max) { if (v < min) return min; if (v > max) return max; return v; } +static inline double asc_clampd(double v, double min, double max) { + if (v < min) return min; + if (v > max) return max; + return v; +} + +#define asc_clamp(v, min, max) _Generic((v), \ + int: asc_clampi, \ + long long int: asc_clampll, \ + unsigned: asc_clampu, \ + unsigned long long int: asc_clampull, \ + float: asc_clampf, \ + double: asc_clampd \ + )(v, min, max) + static inline asc_vec2i asc_rect_center(asc_rect rect) { return ASC_VEC2I(rect.pos.x + rect.size.width/2, rect.pos.y + rect.size.height/2); } @@ -173,10 +206,10 @@ unsigned blue = (unsigned)(255*c.blue); unsigned alpha = (unsigned)(255*c.alpha); asc_col4i r; - r.red = asc_clamp_u(red, 0, 255); - r.green = asc_clamp_u(green, 0, 255); - r.blue = asc_clamp_u(blue, 0, 255); - r.alpha = asc_clamp_u(alpha, 0, 255); + r.red = asc_clamp(red, 0, 255); + r.green = asc_clamp(green, 0, 255); + r.blue = asc_clamp(blue, 0, 255); + r.alpha = asc_clamp(alpha, 0, 255); return r; }