lokinet/llarp/util/bits.hpp

52 lines
1.2 KiB
C++
Raw Normal View History

#ifndef LLARP_BITS_HPP
#define LLARP_BITS_HPP
2019-02-07 00:22:54 +00:00
#include <bitset>
2018-12-15 16:21:52 +00:00
#include <cstddef>
2019-02-07 00:22:54 +00:00
#include <numeric>
#include <type_traits>
2019-02-07 12:31:14 +00:00
#include <limits>
2019-06-11 16:44:05 +00:00
#include <absl/numeric/int128.h>
2018-12-15 16:21:52 +00:00
namespace llarp
{
namespace bits
{
template < typename Int_t >
2018-12-15 16:21:52 +00:00
constexpr std::size_t
2019-02-07 00:22:54 +00:00
count_bits(Int_t i)
{
2019-02-07 00:22:54 +00:00
static_assert(std::is_integral< Int_t >::value,
"Int_t should be an integer");
static_assert(std::is_unsigned< Int_t >::value,
"Int_t should be unsigned");
return std::bitset< std::numeric_limits< Int_t >::digits >(i).count();
}
constexpr std::size_t
count_bits_128(const absl::uint128& i)
{
return count_bits(absl::Uint128High64(i))
+ count_bits(absl::Uint128Low64(i));
}
2019-02-07 00:22:54 +00:00
template < typename InputIt >
2018-12-15 16:21:52 +00:00
constexpr std::size_t
2019-02-07 00:22:54 +00:00
__count_array_bits(InputIt begin, InputIt end)
{
2019-02-07 00:22:54 +00:00
return std::accumulate(begin, end, 0, [](auto acc, auto val) {
return acc + count_bits(val);
});
}
template < typename T >
2018-12-15 16:21:52 +00:00
constexpr std::size_t
count_array_bits(const T& array)
{
2019-02-07 00:22:54 +00:00
return __count_array_bits(std::begin(array), std::end(array));
}
} // namespace bits
} // namespace llarp
#endif