1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 03:47:35 +00:00

LibWeb: Remove implicit conversion from float and double to CSSPixels

In general it is not safe to convert any arbitrary floating-point value
to CSSPixels. CSSPixels has a resolution of 0.015625, which for small
values (e.g. scale factors between 0 and 1), can produce bad results
if converted to CSSPixels then scaled back up. In the worst case values
can underflow to zero and produce incorrect results.
This commit is contained in:
MacDue 2023-08-26 15:03:04 +01:00 committed by Alexander Kalenik
parent 0f9c088302
commit 360c0eb509
43 changed files with 248 additions and 221 deletions

View file

@ -9,6 +9,7 @@
#pragma once
#include <AK/Concepts.h>
#include <AK/Debug.h>
#include <AK/DistinctNumeric.h>
#include <AK/Math.h>
#include <AK/Traits.h>
@ -74,16 +75,16 @@ public:
m_value = static_cast<int>(value) << fractional_bits;
}
CSSPixels(float value)
{
if (!isnan(value))
m_value = AK::clamp_to_int(value * fixed_point_denominator);
}
CSSPixels(double value)
template<FloatingPoint F>
explicit CSSPixels(F value)
{
if (!isnan(value))
m_value = AK::clamp_to_int(value * fixed_point_denominator);
// Note: The resolution of CSSPixels is 0.015625, so care must be taken when converting
// floats/doubles to CSSPixels as small values (such as scale factors) can underflow to zero,
// or otherwise produce inaccurate results (when scaled back up).
if (m_value == 0 && value != 0)
dbgln_if(LIBWEB_CSS_DEBUG, "CSSPixels: Conversion from float or double underflowed to zero");
}
template<Unsigned U>
@ -217,6 +218,32 @@ public:
constexpr CSSPixels abs() const { return from_raw(::abs(m_value)); }
CSSPixels& scale_by(float value)
{
*this = CSSPixels(to_float() * value);
return *this;
}
CSSPixels& scale_by(double value)
{
*this = CSSPixels(to_double() * value);
return *this;
}
CSSPixels scaled(float value) const
{
auto result = *this;
result.scale_by(value);
return result;
}
CSSPixels scaled(double value) const
{
auto result = *this;
result.scale_by(value);
return result;
}
private:
i32 m_value { 0 };
};