ClickHouse/src/Functions/bitHammingDistance.cpp
Robert Schulze a7734672b9
Use std::popcount, ::countl_zero, ::countr_zero functions
- Introduced with the C++20 <bit> header

- The problem with __builtin_c(l|t)z() is that 0 as input has an
  undefined result (*) and the code did not always check. The std::
  versions do not have this issue.

- In some cases, we continue to use buildin_c(l|t)z(), (e.g. in
  src/Common/BitHelpers.h) because the std:: versions only accept
  unsigned inputs (and they also check that) and the casting would be
  ugly.

(*) https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
2022-07-31 15:16:51 +00:00

37 lines
1000 B
C++

#include <Functions/FunctionBinaryArithmetic.h>
#include <Functions/FunctionFactory.h>
#include <bit>
namespace DB
{
template <typename A, typename B>
struct BitHammingDistanceImpl
{
using ResultType = UInt8;
static const constexpr bool allow_fixed_string = false;
static const constexpr bool allow_string_integer = false;
template <typename Result = ResultType>
static inline NO_SANITIZE_UNDEFINED Result apply(A a, B b)
{
UInt64 res = static_cast<UInt64>(a) ^ static_cast<UInt64>(b);
return std::popcount(res);
}
#if USE_EMBEDDED_COMPILER
static constexpr bool compilable = false; /// special type handling, some other time
#endif
};
struct NameBitHammingDistance
{
static constexpr auto name = "bitHammingDistance";
};
using FunctionBitHammingDistance = BinaryArithmeticOverloadResolver<BitHammingDistanceImpl, NameBitHammingDistance>;
REGISTER_FUNCTION(BitHammingDistance)
{
factory.registerFunction<FunctionBitHammingDistance>();
}
}