summaryrefslogtreecommitdiff
path: root/AK
diff options
context:
space:
mode:
authorDaniel Bertalan <dani@danielbertalan.dev>2021-07-05 18:38:17 +0200
committerGunnar Beutner <gunnar@beutner.name>2021-07-08 10:11:00 +0200
commitc6fafd3e90b05e02dd313e93e3d4455f59e46d4d (patch)
treebab16aaf468f0033b38e7e60492a52d8f05264fc /AK
parent62f84e94c8a362a6b3bb4827cb818dee11d8ecf3 (diff)
downloadserenity-c6fafd3e90b05e02dd313e93e3d4455f59e46d4d.zip
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.
Diffstat (limited to 'AK')
-rw-r--r--AK/StdLibExtras.h20
1 files changed, 20 insertions, 0 deletions
diff --git a/AK/StdLibExtras.h b/AK/StdLibExtras.h
index ac074bf72a..30a23b65bd 100644
--- a/AK/StdLibExtras.h
+++ b/AK/StdLibExtras.h
@@ -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;