LibreOffice Module o3tl (master)  1
float_int_conversion.hxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
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/.
8  */
9 
10 #ifndef INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX
11 #define INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX
12 
13 #include <sal/config.h>
14 
15 #include <cmath>
16 #include <type_traits>
17 
18 namespace o3tl
19 {
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)
25 {
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);
31 }
32 
33 // Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no
34 // larger than `max`:
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)
38 {
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);
44 }
45 
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)
50 {
51  return value >= 0 ? std::ceil(value) : std::floor(value);
52 }
53 }
54 
55 #endif
56 
57 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
std::enable_if_t< std::is_floating_point_v< F >, F > roundAway(F value)
std::enable_if_t< std::is_floating_point_v< F > &&std::is_integral_v< I >, bool > convertsToAtMost(F value, I max)
std::enable_if_t< std::is_floating_point_v< F > &&std::is_integral_v< I >, bool > convertsToAtLeast(F value, I min)