tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
saturate_cast.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2024 Tobias Hienzsch
3
4#ifndef TETL_NUMERIC_SATURATE_CAST_HPP
5#define TETL_NUMERIC_SATURATE_CAST_HPP
6
7#include <etl/_concepts/builtin_integer.hpp>
8#include <etl/_limits/numeric_limits.hpp>
9#include <etl/_utility/cmp_greater.hpp>
10#include <etl/_utility/cmp_less.hpp>
11
12namespace etl {
13
14/// Converts the value x to a value of type T, clamping x between
15/// the minimum and maximum values of type T.
16///
17/// \ingroup numeric
18template <builtin_integer To, builtin_integer From>
19[[nodiscard]] constexpr auto saturate_cast(From x) noexcept -> To
20{
21 if (etl::cmp_less(x, etl::numeric_limits<To>::min())) {
22 return etl::numeric_limits<To>::min();
23 }
24 if (etl::cmp_greater(x, etl::numeric_limits<To>::max())) {
25 return etl::numeric_limits<To>::max();
26 }
27 return static_cast<To>(x);
28}
29
30} // namespace etl
31
32#endif // TETL_NUMERIC_SATURATE_CAST_HPP
constexpr auto saturate_cast(From x) noexcept -> To
Converts the value x to a value of type T, clamping x between the minimum and maximum values of type ...
Definition saturate_cast.hpp:19
Definition adjacent_find.hpp:9
Definition numeric_limits.hpp:18