From 77ac41708b5933cb81b5bd42eed00f199060532e Mon Sep 17 00:00:00 2001 From: Evgenii Kliuchnikov Date: Fri, 8 May 2026 13:42:13 +0000 Subject: [PATCH] Update Safe{Add,Mul} to match libjxl --- lib/base/common.h | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/base/common.h b/lib/base/common.h index f5a7a283..34fdfd43 100644 --- a/lib/base/common.h +++ b/lib/base/common.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -33,13 +34,23 @@ constexpr inline size_t RoundUpToBlockDim(size_t dim) { return (dim + 7) & ~static_cast(7); } -static inline bool JPEGLI_MAYBE_UNUSED SafeAdd(const uint64_t a, - const uint64_t b, - uint64_t& sum) { +template ::value>::type> +static inline bool SafeAdd(const U a, const U b, U& sum) { sum = a + b; return sum >= a; // no need to check b - either sum >= both or < both. } +template ::value>::type> +static inline bool SafeMul(const U a, const U b, U& product) { + product = 0; + if (a == 0 || b == 0) return true; + if (b > (std::numeric_limits::max() / a)) return false; + product = a * b; + return true; +} + template constexpr inline T1 DivCeil(T1 a, T2 b) { return (a + b - 1) / b;