ClickHouse

Форк
0
/
bitCount.cpp 
63 строки · 1.9 Кб
1
#include <base/bit_cast.h>
2
#include <Functions/FunctionFactory.h>
3
#include <Functions/FunctionUnaryArithmetic.h>
4
#include <bit>
5

6

7
namespace DB
8
{
9

10
template <typename A>
11
struct BitCountImpl
12
{
13
    using ResultType = std::conditional_t<(sizeof(A) * 8 >= 256), UInt16, UInt8>;
14
    static constexpr bool allow_string_or_fixed_string = true;
15

16
    static inline ResultType apply(A a)
17
    {
18
        /// We count bits in the value representation in memory. For example, we support floats.
19
        /// We need to avoid sign-extension when converting signed numbers to larger type. So, uint8_t(-1) has 8 bits.
20

21
        if constexpr (is_big_int_v<A>)
22
        {
23
            ResultType res = 0;
24
            for (auto item : a.items)
25
                res += std::popcount(item);
26
            return res;
27
        }
28
        if constexpr (std::is_same_v<A, UInt64> || std::is_same_v<A, Int64>)
29
            return std::popcount(static_cast<UInt64>(a));
30
        if constexpr (std::is_same_v<A, UInt32> || std::is_same_v<A, Int32> || std::is_unsigned_v<A>)
31
            return std::popcount(static_cast<UInt32>(a));
32
        if constexpr (std::is_same_v<A, Int16>)
33
            return std::popcount(static_cast<UInt16>(a));
34
        if constexpr (std::is_same_v<A, Int8>)
35
            return std::popcount(static_cast<uint8_t>(a));
36
        else
37
            return std::popcount(bit_cast<uint64_t>(a));
38
    }
39

40
#if USE_EMBEDDED_COMPILER
41
    static constexpr bool compilable = false;
42
#endif
43
};
44

45
struct NameBitCount { static constexpr auto name = "bitCount"; };
46
using FunctionBitCount = FunctionUnaryArithmetic<BitCountImpl, NameBitCount, false /* is injective */>;
47

48
/// The function has no ranges of monotonicity.
49
template <> struct FunctionUnaryArithmeticMonotonicity<NameBitCount>
50
{
51
    static bool has() { return false; }
52
    static IFunction::Monotonicity get(const Field &, const Field &)
53
    {
54
        return {};
55
    }
56
};
57

58
REGISTER_FUNCTION(BitCount)
59
{
60
    factory.registerFunction<FunctionBitCount>();
61
}
62

63
}
64

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.