ClickHouse/src/Functions/bitCount.cpp

62 lines
1.8 KiB
C++
Raw Normal View History

2021-10-02 07:13:14 +00:00
#include <base/bit_cast.h>
2020-01-17 19:57:03 +00:00
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionUnaryArithmetic.h>
namespace DB
{
2020-09-07 18:00:37 +00:00
namespace
{
2020-01-17 19:57:03 +00:00
template <typename A>
struct BitCountImpl
{
using ResultType = UInt8;
2020-02-14 08:17:32 +00:00
static constexpr bool allow_fixed_string = false;
static const constexpr bool allow_string_integer = false;
2020-01-17 19:57:03 +00:00
static inline ResultType apply(A a)
{
2020-01-17 20:00:46 +00:00
/// We count bits in the value representation in memory. For example, we support floats.
/// We need to avoid sign-extension when converting signed numbers to larger type. So, uint8_t(-1) has 8 bits.
if constexpr (std::is_same_v<A, UInt64> || std::is_same_v<A, Int64>)
return __builtin_popcountll(a);
if constexpr (std::is_same_v<A, UInt32> || std::is_same_v<A, Int32> || std::is_unsigned_v<A>)
return __builtin_popcount(a);
if constexpr (std::is_same_v<A, Int16>)
return __builtin_popcount(static_cast<UInt16>(a));
if constexpr (std::is_same_v<A, Int8>)
return __builtin_popcount(static_cast<UInt8>(a));
else
2021-06-15 19:55:21 +00:00
return __builtin_popcountll(bit_cast<uint64_t>(a));
2020-01-17 19:57:03 +00:00
}
#if USE_EMBEDDED_COMPILER
static constexpr bool compilable = false;
#endif
};
struct NameBitCount { static constexpr auto name = "bitCount"; };
2020-01-17 22:05:27 +00:00
using FunctionBitCount = FunctionUnaryArithmetic<BitCountImpl, NameBitCount, false /* is injective */>;
2020-01-17 19:57:03 +00:00
2020-09-07 18:00:37 +00:00
}
2020-01-17 19:57:03 +00:00
/// The function has no ranges of monotonicity.
template <> struct FunctionUnaryArithmeticMonotonicity<NameBitCount>
{
static bool has() { return false; }
static IFunction::Monotonicity get(const Field &, const Field &)
{
return {};
}
};
void registerFunctionBitCount(FunctionFactory & factory)
{
factory.registerFunction<FunctionBitCount>();
}
}