1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #ifndef INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX
11 #define INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX
13 #include <sal/config.h>
16 #include <type_traits>
20 // Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no
21 // smaller than `min`:
22 template <typename F
, typename I
>
23 std::enable_if_t
<std::is_floating_point_v
<F
> && std::is_integral_v
<I
>, bool>
24 convertsToAtLeast(F value
, I min
)
26 // If `F(min)`, `F(min) - F(1)` are too large in magnitude for `F`'s precision, then they either
27 // fall into the same bucket, in which case we should return false if `value` represents that
28 // bucket, or they are on the boundary of two adjacent buckets, in which case we should return
29 // true if `value`represents the higher bucket containing `F(min)`:
30 return value
> F(min
) - F(1);
33 // Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no
35 template <typename F
, typename I
>
36 std::enable_if_t
<std::is_floating_point_v
<F
> && std::is_integral_v
<I
>, bool>
37 convertsToAtMost(F value
, I max
)
39 // If `F(max)`, `F(max) + F(1)` are too large in magnitude for `F`'s precision, then they either
40 // fall into the same bucket, in which case we should return false if `value` represents that
41 // bucket, or they are on the boundary of two adjacent buckets, in which case we should return
42 // true if `value`represents the lower bucket containing `F(max)`:
43 return value
< F(max
) + F(1);
46 // Return `value` of floating-point type `F` rounded to the nearest integer away from zero (which
47 // can be useful in calls to convertsToAtLeast/Most(roundAway(x), n), to reject x that are
48 // smaller/larger than n because they have a fractional part):
49 template <typename F
> std::enable_if_t
<std::is_floating_point_v
<F
>, F
> roundAway(F value
)
51 return value
>= 0 ? std::ceil(value
) : std::floor(value
);
57 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */