2021-03-09 22:24:35 +00:00
|
|
|
#pragma once
|
2018-08-24 16:07:17 +00:00
|
|
|
|
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>
|
2021-03-09 22:24:35 +00:00
|
|
|
#include <llarp/net/uint128.hpp>
|
|
|
|
#include <llarp/net/net_int.hpp>
|
2018-12-15 16:21:52 +00:00
|
|
|
|
2018-08-24 16:07:17 +00:00
|
|
|
namespace llarp
|
|
|
|
{
|
|
|
|
namespace bits
|
|
|
|
{
|
2020-04-07 18:38:56 +00:00
|
|
|
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)
|
2018-08-24 16:07:17 +00:00
|
|
|
{
|
2020-04-07 18:38:56 +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();
|
2018-08-24 16:07:17 +00:00
|
|
|
}
|
|
|
|
|
2019-09-03 15:56:56 +00:00
|
|
|
constexpr std::size_t
|
2020-02-23 19:35:25 +00:00
|
|
|
count_bits_128(const uint128_t& i)
|
2019-09-03 15:56:56 +00:00
|
|
|
{
|
2020-02-23 19:35:25 +00:00
|
|
|
return count_bits(i.upper) + count_bits(i.lower);
|
2019-09-03 15:56:56 +00:00
|
|
|
}
|
|
|
|
|
2020-06-24 13:24:07 +00:00
|
|
|
template <>
|
|
|
|
constexpr std::size_t
|
|
|
|
count_bits(huint32_t x)
|
|
|
|
{
|
|
|
|
return count_bits(x.h);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
constexpr std::size_t
|
|
|
|
count_bits(nuint32_t x)
|
|
|
|
{
|
|
|
|
return count_bits(x.n);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
constexpr std::size_t
|
|
|
|
count_bits(huint128_t x)
|
|
|
|
{
|
|
|
|
return count_bits_128(x.h);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
constexpr std::size_t
|
|
|
|
count_bits(nuint128_t x)
|
|
|
|
{
|
|
|
|
return count_bits_128(x.n);
|
|
|
|
}
|
|
|
|
|
2020-04-07 18:38:56 +00:00
|
|
|
template <typename InputIt>
|
2018-12-15 16:21:52 +00:00
|
|
|
constexpr std::size_t
|
2020-02-23 19:35:41 +00:00
|
|
|
count_array_bits_impl(InputIt begin, InputIt end)
|
2018-08-24 16:07:17 +00:00
|
|
|
{
|
2020-04-07 18:38:56 +00:00
|
|
|
return std::accumulate(
|
|
|
|
begin, end, 0, [](auto acc, auto val) { return acc + count_bits(val); });
|
2018-08-24 16:07:17 +00:00
|
|
|
}
|
|
|
|
|
2020-04-07 18:38:56 +00:00
|
|
|
template <typename T>
|
2018-12-15 16:21:52 +00:00
|
|
|
constexpr std::size_t
|
2018-08-24 16:07:17 +00:00
|
|
|
count_array_bits(const T& array)
|
|
|
|
{
|
2020-02-23 19:35:41 +00:00
|
|
|
return count_array_bits_impl(std::begin(array), std::end(array));
|
2018-08-24 16:07:17 +00:00
|
|
|
}
|
|
|
|
} // namespace bits
|
|
|
|
} // namespace llarp
|