summaryrefslogtreecommitdiff
path: root/include/o3tl
diff options
context:
space:
mode:
authorMike Kaganski <mike.kaganski@collabora.com>2021-08-24 15:58:15 +0200
committerMike Kaganski <mike.kaganski@collabora.com>2021-08-25 17:12:14 +0200
commite9ab5a5e4e725a348a4276b72fda63cdac2a131c (patch)
tree9579178de0f9a8af32474c93a4a85a5c7c91d828 /include/o3tl
parentc1ad429d925855c1baacbdeca1ef42f4486eb9c2 (diff)
Introduce o3tl::saturating_cast for floating-point->integer conversion
Change-Id: I73191e5ab25fdd9fd8a788db9858b5eb9d3ab955 Reviewed-on: https://gerrit.libreoffice.org/c/core/+/120885 Tested-by: Jenkins Reviewed-by: Mike Kaganski <mike.kaganski@collabora.com>
Diffstat (limited to 'include/o3tl')
-rw-r--r--include/o3tl/float_int_conversion.hxx18
1 files changed, 16 insertions, 2 deletions
diff --git a/include/o3tl/float_int_conversion.hxx b/include/o3tl/float_int_conversion.hxx
index dfaea5ce3bd2..36bce97dd742 100644
--- a/include/o3tl/float_int_conversion.hxx
+++ b/include/o3tl/float_int_conversion.hxx
@@ -20,7 +20,7 @@ namespace o3tl
// Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no
// smaller than `min`:
template <typename F, typename I>
-std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>, bool>
+constexpr std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>, bool>
convertsToAtLeast(F value, I min)
{
// If `F(min)`, `F(min) - F(1)` are too large in magnitude for `F`'s precision, then they either
@@ -33,7 +33,7 @@ convertsToAtLeast(F value, I min)
// Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no
// larger than `max`:
template <typename F, typename I>
-std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>, bool>
+constexpr std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>, bool>
convertsToAtMost(F value, I max)
{
// If `F(max)`, `F(max) + F(1)` are too large in magnitude for `F`'s precision, then they either
@@ -43,6 +43,20 @@ convertsToAtMost(F value, I max)
return value < F(max) + F(1);
}
+// Casts a floating-point to an integer, avoiding overflow. Used like:
+// sal_Int64 n = o3tl::saturating_cast<sal_Int64>(f);
+template <typename I, typename F>
+constexpr std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>, I>
+saturating_cast(F f)
+{
+ if constexpr (std::is_signed_v<I>)
+ if (!convertsToAtLeast(f, std::numeric_limits<I>::min()))
+ return std::numeric_limits<I>::min();
+ if (!convertsToAtMost(f, std::numeric_limits<I>::max()))
+ return std::numeric_limits<I>::max();
+ return f;
+}
+
// Return `value` of floating-point type `F` rounded to the nearest integer away from zero (which
// can be useful in calls to convertsToAtLeast/Most(roundAway(x), n), to reject x that are
// smaller/larger than n because they have a fractional part):