tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
popcount.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_POPCOUNT_HPP
5#define TETL_BIT_POPCOUNT_HPP
6
7#include <etl/_config/all.hpp>
8
9#include <etl/_concepts/builtin_unsigned_integer.hpp>
10#include <etl/_limits/numeric_limits.hpp>
11#include <etl/_type_traits/is_constant_evaluated.hpp>
12#include <etl/_type_traits/is_same.hpp>
13
14namespace etl {
15
16namespace detail {
17
18// https://en.wikichip.org/wiki/population_count
19template <etl::builtin_unsigned_integer UInt>
20[[nodiscard]] constexpr auto popcount_fallback(UInt val) noexcept -> int
21{
22 auto c = 0;
23 for (; val != 0; val &= val - UInt(1)) {
24 c++;
25 }
26 return c;
27}
28
29} // namespace detail
30
31/// \brief Returns the number of 1 bits in the value of x.
32///
33/// \details This overload only participates in overload resolution if UInt is an
34/// unsigned integer type (that is, unsigned char, unsigned short, unsigned int,
35/// unsigned long, unsigned long long, or an extended unsigned integer type).
36///
37/// \ingroup bit
38template <etl::builtin_unsigned_integer UInt>
39[[nodiscard]] constexpr auto popcount(UInt val) noexcept -> int
40{
42#if __has_builtin(__builtin_popcount)
43 if constexpr (sizeof(UInt) == sizeof(unsigned long long)) {
44 return static_cast<int>(__builtin_popcountll(val));
45 } else if constexpr (sizeof(UInt) == sizeof(unsigned long)) {
46 return static_cast<int>(__builtin_popcountl(val));
47 } else {
48 return static_cast<int>(__builtin_popcount(val));
49 }
50#endif
51 }
52
53 return etl::detail::popcount_fallback(val);
54}
55
56} // namespace etl
57
58#endif // TETL_BIT_POPCOUNT_HPP
constexpr auto popcount(UInt val) noexcept -> int
Returns the number of 1 bits in the value of x.
Definition popcount.hpp:39
Definition adjacent_find.hpp:9
constexpr auto is_constant_evaluated() noexcept -> bool
Detects whether the function call occurs within a constant-evaluated context. Returns true if the eva...
Definition is_constant_evaluated.hpp:17