tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
bit_ceil.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2019 Tobias Hienzsch
3
4#ifndef TETL_BIT_BIT_CEIL_HPP
5#define TETL_BIT_BIT_CEIL_HPP
6
7#include <etl/_bit/bit_width.hpp>
8#include <etl/_concepts/builtin_unsigned_integer.hpp>
9#include <etl/_limits/numeric_limits.hpp>
10
11namespace etl {
12
13/// \brief Calculates the smallest integral power of two that is not smaller
14/// than x. If that value is not representable in UInt, the behavior is undefined.
15/// Call to this function is permitted in constant evaluation only if the
16/// undefined behavior does not occur.
17///
18/// \details This overload only participates in overload resolution if UInt is an
19/// unsigned integer type (that is, unsigned char, unsigned short, unsigned int,
20/// unsigned long, unsigned long long, or an extended unsigned integer type).
21///
22/// \returns The smallest integral power of two that is not smaller than x.
23///
24/// \ingroup bit
25template <etl::builtin_unsigned_integer UInt>
26[[nodiscard]] constexpr auto bit_ceil(UInt x) noexcept -> UInt
27{
28 if (x <= 1U) {
29 return UInt{1};
30 }
31 if constexpr (is_same_v<UInt, decltype(+x)>) {
32 return UInt{1U} << bit_width(UInt{x - 1U});
33 } else {
34 // for types subject to integral promotion
35 auto o = etl::numeric_limits<unsigned>::digits - etl::numeric_limits<UInt>::digits;
36 return UInt{1U << (bit_width(UInt{x - 1U}) + o) >> o};
37 }
38}
39
40} // namespace etl
41
42#endif // TETL_BIT_BIT_CEIL_HPP
constexpr auto bit_ceil(UInt x) noexcept -> UInt
Calculates the smallest integral power of two that is not smaller than x. If that value is not repres...
Definition bit_ceil.hpp:26
Definition adjacent_find.hpp:9
static constexpr int digits
Definition numeric_limits.hpp:687
Definition numeric_limits.hpp:18