cloudflare/ClickHouse
Publicmirrored fromhttps://github.com/cloudflare/ClickHouse
src/Functions/abs.cpp
55lines · modecode
6 years ago
| 1 | #include <Functions/FunctionFactory.h> |
| 2 | #include <Functions/FunctionUnaryArithmetic.h> |
| 3 | #include <DataTypes/NumberTraits.h> |
| 4 | #include <Common/FieldVisitors.h> |
| 5 | |
| 6 | namespace DB |
| 7 | { |
| 8 | |
| 9 | template <typename A> |
| 10 | struct AbsImpl |
| 11 | { |
| 12 | using ResultType = std::conditional_t<IsDecimalNumber<A>, A, typename NumberTraits::ResultOfAbs<A>::Type>; |
| 13 | static const constexpr bool allow_fixed_string = false; |
| 14 | |
| 15 | static inline NO_SANITIZE_UNDEFINED ResultType apply(A a) |
| 16 | { |
| 17 | if constexpr (IsDecimalNumber<A>) |
| 18 | return a < 0 ? A(-a) : a; |
| 19 | else if constexpr (is_integral_v<A> && is_signed_v<A>) |
| 20 | return a < 0 ? static_cast<ResultType>(~a) + 1 : a; |
| 21 | else if constexpr (is_integral_v<A> && is_unsigned_v<A>) |
| 22 | return static_cast<ResultType>(a); |
| 23 | else if constexpr (std::is_floating_point_v<A>) |
| 24 | return static_cast<ResultType>(std::abs(a)); |
| 25 | } |
| 26 | |
| 27 | #if USE_EMBEDDED_COMPILER |
| 28 | static constexpr bool compilable = false; /// special type handling, some other time |
| 29 | #endif |
| 30 | }; |
| 31 | |
| 32 | struct NameAbs { static constexpr auto name = "abs"; }; |
| 33 | using FunctionAbs = FunctionUnaryArithmetic<AbsImpl, NameAbs, false>; |
| 34 | |
| 35 | template <> struct FunctionUnaryArithmeticMonotonicity<NameAbs> |
| 36 | { |
| 37 | static bool has() { return true; } |
| 38 | static IFunction::Monotonicity get(const Field & left, const Field & right) |
| 39 | { |
| 40 | Float64 left_float = left.isNull() ? -std::numeric_limits<Float64>::infinity() : applyVisitor(FieldVisitorConvertToNumber<Float64>(), left); |
| 41 | Float64 right_float = right.isNull() ? std::numeric_limits<Float64>::infinity() : applyVisitor(FieldVisitorConvertToNumber<Float64>(), right); |
| 42 | |
| 43 | if ((left_float < 0 && right_float > 0) || (left_float > 0 && right_float < 0)) |
| 44 | return {}; |
| 45 | |
| 46 | return { true, (left_float > 0) }; |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | void registerFunctionAbs(FunctionFactory & factory) |
| 51 | { |
| 52 | factory.registerFunction<FunctionAbs>(FunctionFactory::CaseInsensitive); |
| 53 | } |
| 54 | |
| 55 | } |