blob: 607c67b742e5151595eea9c6d9f365bfa58f0190 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#include <type_traits>
#include <base/bit_cast.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionUnaryArithmetic.h>
namespace DB
{
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
}
namespace
{
template <typename T>
requires std::is_integral_v<T> && (sizeof(T) <= sizeof(UInt32))
inline T roundDownToPowerOfTwo(T x)
{
return x <= 0 ? 0 : (T(1) << (31 - __builtin_clz(x)));
}
template <typename T>
requires std::is_integral_v<T> && (sizeof(T) == sizeof(UInt64))
inline T roundDownToPowerOfTwo(T x)
{
return x <= 0 ? 0 : (T(1) << (63 - __builtin_clzll(x)));
}
template <typename T>
requires std::is_same_v<T, Float32>
inline T roundDownToPowerOfTwo(T x)
{
return bit_cast<T>(bit_cast<UInt32>(x) & ~((1ULL << 23) - 1));
}
template <typename T>
requires std::is_same_v<T, Float64>
inline T roundDownToPowerOfTwo(T x)
{
return bit_cast<T>(bit_cast<UInt64>(x) & ~((1ULL << 52) - 1));
}
template <typename T>
requires is_big_int_v<T>
inline T roundDownToPowerOfTwo(T)
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "roundToExp2() for big integers is not implemented");
}
/** For integer data types:
* - if number is greater than zero, round it down to nearest power of two (example: roundToExp2(100) = 64, roundToExp2(64) = 64);
* - otherwise, return 0.
*
* For floating point data types: zero out mantissa, but leave exponent.
* - if number is greater than zero, round it down to nearest power of two (example: roundToExp2(3) = 2);
* - negative powers are also used (example: roundToExp2(0.7) = 0.5);
* - if number is zero, return zero;
* - if number is less than zero, the result is symmetrical: roundToExp2(x) = -roundToExp2(-x). (example: roundToExp2(-0.3) = -0.25);
*/
template <typename T>
struct RoundToExp2Impl
{
using ResultType = T;
static constexpr const bool allow_string_or_fixed_string = false;
static inline T apply(T x)
{
return roundDownToPowerOfTwo<T>(x);
}
#if USE_EMBEDDED_COMPILER
static constexpr bool compilable = false;
#endif
};
struct NameRoundToExp2 { static constexpr auto name = "roundToExp2"; };
using FunctionRoundToExp2 = FunctionUnaryArithmetic<RoundToExp2Impl, NameRoundToExp2, false>;
}
template <> struct FunctionUnaryArithmeticMonotonicity<NameRoundToExp2> : PositiveMonotonicity {};
REGISTER_FUNCTION(RoundToExp2)
{
factory.registerFunction<FunctionRoundToExp2>();
}
}
|