From 4dd6867532b3e1b43ee5d5efc2f06912aff4cdf0 Mon Sep 17 00:00:00 2001 From: Rahim Kanji Date: Sun, 27 Oct 2024 18:24:14 +0500 Subject: [PATCH] Added overflow_safe_multiply() --- include/gen_utils.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/include/gen_utils.h b/include/gen_utils.h index 4eb6e1c9c0..3b2cea7708 100644 --- a/include/gen_utils.h +++ b/include/gen_utils.h @@ -314,6 +314,18 @@ inline unsigned long long realtime_time() { return (((unsigned long long) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000); } +template +inline T overflow_safe_multiply(T val) { + static_assert(std::is_integral::value, "T must be an integer type."); + static_assert(std::is_unsigned_v, "T must be an unsigned integer type."); + static_assert(FACTOR > 0, "Negative factors are not supported."); + + if constexpr (FACTOR == 0) return 0; + if (val == 0) return 0; + if (val > std::numeric_limits::max() / FACTOR) return std::numeric_limits::max(); + return (val * FACTOR); +} + #endif /* __GEN_FUNCTIONS */ bool Proxy_file_exists(const char *);