| 1 |
/* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */ |
| 2 |
|
| 3 |
#ifndef MPT_BASE_SATURATE_ROUND_HPP |
| 4 |
#define MPT_BASE_SATURATE_ROUND_HPP |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
#include "mpt/base/namespace.hpp" |
| 9 |
|
| 10 |
#include "mpt/base/math.hpp" |
| 11 |
|
| 12 |
#include <limits> |
| 13 |
#include <type_traits> |
| 14 |
|
| 15 |
#include <cmath> |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
namespace mpt { |
| 20 |
inline namespace MPT_INLINE_NS { |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
template <typename Tdst, typename Tsrc> |
| 25 |
constexpr Tdst saturate_trunc(Tsrc src) { |
| 26 |
static_assert(std::is_floating_point<Tsrc>::value); |
| 27 |
if (src >= static_cast<Tsrc>(std::numeric_limits<Tdst>::max())) { |
| 28 |
return std::numeric_limits<Tdst>::max(); |
| 29 |
} |
| 30 |
if (src <= static_cast<Tsrc>(std::numeric_limits<Tdst>::min())) { |
| 31 |
return std::numeric_limits<Tdst>::min(); |
| 32 |
} |
| 33 |
return static_cast<Tdst>(src); |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
// Rounds given double value to nearest integer value of type T. |
| 38 |
// Out-of-range values are saturated to the specified integer type's limits. |
| 39 |
|
| 40 |
template <typename Tdst, typename Tsrc> |
| 41 |
inline Tdst saturate_round(Tsrc val) { |
| 42 |
static_assert(std::is_floating_point<Tsrc>::value); |
| 43 |
static_assert(std::numeric_limits<Tdst>::is_integer); |
| 44 |
return mpt::saturate_trunc<Tdst>(mpt::round(val)); |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
template <typename Tdst, typename Tsrc> |
| 49 |
inline Tdst saturate_ceil(Tsrc val) { |
| 50 |
static_assert(std::is_floating_point<Tsrc>::value); |
| 51 |
static_assert(std::numeric_limits<Tdst>::is_integer); |
| 52 |
return mpt::saturate_trunc<Tdst>(std::ceil(val)); |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
template <typename Tdst, typename Tsrc> |
| 57 |
inline Tdst saturate_floor(Tsrc val) { |
| 58 |
static_assert(std::is_floating_point<Tsrc>::value); |
| 59 |
static_assert(std::numeric_limits<Tdst>::is_integer); |
| 60 |
return mpt::saturate_trunc<Tdst>(std::floor(val)); |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
} // namespace MPT_INLINE_NS |
| 65 |
} // namespace mpt |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
#endif // MPT_BASE_SATURATE_ROUND_HPP |