mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
AK: Prevent overflow of the min when clamping unsigned values to signed
Also, add some tests for the cases that were broken before.
This commit is contained in:
parent
172f4588a7
commit
bbd8a218a5
Notes:
sideshowbarker
2024-07-17 03:19:14 +09:00
Author: https://github.com/Zaggy1024 Commit: https://github.com/LadybirdBrowser/ladybird/commit/bbd8a218a5 Pull-request: https://github.com/LadybirdBrowser/ladybird/pull/230 Reviewed-by: https://github.com/ADKaster
2 changed files with 12 additions and 4 deletions
14
AK/Math.h
14
AK/Math.h
|
@ -1008,11 +1008,17 @@ constexpr T pow(T x, T y)
|
|||
template<Integral I, typename T>
|
||||
constexpr I clamp_to(T value)
|
||||
{
|
||||
if (value >= static_cast<T>(NumericLimits<I>::max()))
|
||||
return NumericLimits<I>::max();
|
||||
constexpr auto max = static_cast<T>(NumericLimits<I>::max());
|
||||
if constexpr (max > 0) {
|
||||
if (value >= static_cast<T>(NumericLimits<I>::max()))
|
||||
return NumericLimits<I>::max();
|
||||
}
|
||||
|
||||
if (value <= static_cast<T>(NumericLimits<I>::min()))
|
||||
return NumericLimits<I>::min();
|
||||
constexpr auto min = static_cast<T>(NumericLimits<I>::min());
|
||||
if constexpr (min <= 0) {
|
||||
if (value <= static_cast<T>(NumericLimits<I>::min()))
|
||||
return NumericLimits<I>::min();
|
||||
}
|
||||
|
||||
if constexpr (IsFloatingPoint<T>)
|
||||
return round_to<I>(value);
|
||||
|
|
|
@ -119,9 +119,11 @@ TEST_CASE(ceil_log2)
|
|||
|
||||
TEST_CASE(clamp_to)
|
||||
{
|
||||
EXPECT_EQ((AK::clamp_to<i32>(1000000u)), 1000000);
|
||||
EXPECT_EQ((AK::clamp_to<i32>(NumericLimits<u64>::max())), NumericLimits<i32>::max());
|
||||
|
||||
EXPECT_EQ((AK::clamp_to<u32>(-10)), 0u);
|
||||
EXPECT_EQ((AK::clamp_to<u32>(10)), 10u);
|
||||
|
||||
EXPECT_EQ((AK::clamp_to<i32>(NumericLimits<i64>::min())), NumericLimits<i32>::min());
|
||||
EXPECT_EQ((AK::clamp_to<i32>(NumericLimits<i64>::max())), NumericLimits<i32>::max());
|
||||
|
|
Loading…
Reference in a new issue