From 291b7ef1e06fb07ce252e5b7b44f8062a0f85381 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Wed, 12 Aug 2026 17:23:05 -0600 Subject: [PATCH] [algs] Complete signed saturation helpers Add an always-inline saturating negation for position values that can reach INT_MIN. Also require the floating-point clamp helper to inline, matching the add and subtract helpers used throughout shaping. Extend the boundary tests for both helpers. This supports the complete position-overflow fix for issue #6151. Testing: meson test -C build --print-errorlogs Assisted-by: Codex --- src/hb-algs.hh | 11 ++++++++++- src/test-algs.cc | 6 ++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/hb-algs.hh b/src/hb-algs.hh index 1d2bdebb9..514ce71b8 100644 --- a/src/hb-algs.hh +++ b/src/hb-algs.hh @@ -937,11 +937,20 @@ hb_saturate_sub (T a, T b) return b < 0 ? hb_int_max (T) : hb_int_min (T); } +template +static HB_ALWAYS_INLINE T +hb_saturate_neg (T a) +{ + static_assert (std::is_integral::value && std::is_signed::value, ""); + + return hb_saturate_sub ((T) 0, a); +} + /* Convert a floating-point value to integer type T, saturating to T's * range instead of relying on the undefined behavior of an out-of-range * float-to-int conversion. NaN saturates to the minimum of T. */ template -static inline T +static HB_ALWAYS_INLINE T hb_clamp_to (double v) { return (T) hb_clamp (v, diff --git a/src/test-algs.cc b/src/test-algs.cc index 4a94afd4d..66cd1c9d5 100644 --- a/src/test-algs.cc +++ b/src/test-algs.cc @@ -96,6 +96,12 @@ main (int argc, char **argv) hb_always_assert (hb_saturate_sub (INT_MAX, -1) == INT_MAX); hb_always_assert (hb_saturate_sub (INT_MIN, 1) == INT_MIN); hb_always_assert (hb_saturate_sub (INT_MIN, INT_MIN) == 0); + hb_always_assert (hb_saturate_neg (2) == -2); + hb_always_assert (hb_saturate_neg (-2) == 2); + hb_always_assert (hb_saturate_neg (INT_MIN) == INT_MAX); + hb_always_assert (hb_clamp_to (1.) == 1); + hb_always_assert (hb_clamp_to ((double) INT_MAX + 1.) == INT_MAX); + hb_always_assert (hb_clamp_to ((double) INT_MIN - 1.) == INT_MIN); x = 1; hb_always_assert (++hb_inc (x) == 3);