From f253e078118fd77abf44f12d1813099c805ee15d Mon Sep 17 00:00:00 2001 From: Rahim Kanji Date: Fri, 8 Nov 2024 00:05:48 +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 33f5afc34..11a58026e 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 *);