1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 08:44:58 +00:00

AK+Userland: Add generic AK::abs() function and use it

Previously, in LibGFX's `Point` class, calculated distances were passed
to the integer `abs` function, even if the stored type was a float. This
caused the value to unexpectedly be truncated. Luckily, this API was not
used with floating point types, but that can change in the future, so
why not fix it now :^)

Since we are in C++, we can use function overloading to make things
easy, and to automatically use the right version.

This is even better than the LibC/LibM functions, as using a bit of
hackery, they are able to be constant-evaluated. They use compiler
intrinsics, so they do not depend on external code and the compiler can
emit the most optimized code by default.

Since we aren't using the C++ standard library's trick of importing
everything into the `AK` namespace, this `abs` function cannot be
exported to the global namespace, as the names would clash.
This commit is contained in:
Daniel Bertalan 2021-07-05 18:38:17 +02:00 committed by Gunnar Beutner
parent 62f84e94c8
commit c6fafd3e90
5 changed files with 29 additions and 9 deletions

View file

@ -125,6 +125,26 @@ constexpr bool is_constant_evaluated()
#endif
}
// These can't be exported into the global namespace as they would clash with the C standard library.
#define __DEFINE_GENERIC_ABS(type, zero, intrinsic) \
constexpr type abs(type num) \
{ \
if (is_constant_evaluated()) \
return num < zero ? -num : num; \
else \
return __builtin_##intrinsic(num); \
}
__DEFINE_GENERIC_ABS(int, 0, abs);
__DEFINE_GENERIC_ABS(long, 0l, labs);
__DEFINE_GENERIC_ABS(long long, 0ll, llabs);
#ifndef KERNEL
__DEFINE_GENERIC_ABS(float, 0.0f, fabsf);
__DEFINE_GENERIC_ABS(double, 0.0, fabs);
__DEFINE_GENERIC_ABS(long double, 0.0l, fabsl);
#endif
}
using AK::array_size;