Skip to content

Commit

Permalink
Fix decimal add (#344)
Browse files Browse the repository at this point in the history
* fix decimal add
* remove unused code
  • Loading branch information
zhejiangxiaomai authored Jul 3, 2023
1 parent d4aa8a2 commit b32cc11
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
1 change: 0 additions & 1 deletion velox/functions/sparksql/DecimalArithmetic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,6 @@ class Addition {
auto multiplier = DecimalUtil::kPowersOfTen[higher_scale];
if (aRightScaled >= multiplier - bRightScaled) {
right = R(aRightScaled - (multiplier - bRightScaled));
std::cout << "carry to 1" << std::endl;
carry_to_left = 1;
} else {
right = R(aRightScaled + bRightScaled);
Expand Down
32 changes: 30 additions & 2 deletions velox/type/DecimalUtilOp.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,32 @@ class DecimalUtilOp {
return std::min(x_lz, y_lz);
}

template <class T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
FOLLY_ALWAYS_INLINE static int64_t
multiply(int64_t a, int64_t b, bool* overflow) {
int64_t value;
*overflow = __builtin_mul_overflow(a, b, &value);
if (!*overflow && value >= velox::DecimalUtil::kShortDecimalMin &&
value <= velox::DecimalUtil::kShortDecimalMax) {
return value;
}
*overflow = true;
return -1;
}

template <class T, typename = std::enable_if_t<std::is_same_v<T, int128_t>>>
FOLLY_ALWAYS_INLINE static int128_t
multiply(int128_t a, int128_t b, bool* overflow) {
int128_t value;
*overflow = __builtin_mul_overflow(a, b, &value);
if (!*overflow && value >= velox::DecimalUtil::kLongDecimalMin &&
value <= velox::DecimalUtil::kLongDecimalMax) {
return value;
}
*overflow = true;
return -1;
}

template <typename R, typename A, typename B>
inline static R divideWithRoundUp(
R& r,
Expand Down Expand Up @@ -175,8 +201,10 @@ class DecimalUtilOp {
}
auto bitsRequiredAfterScaling = maxBitsRequiredAfterScaling<A>(a, aRescale);
if (bitsRequiredAfterScaling <= 127) {
unsignedDividendRescaled = checkedMultiply<R>(
unsignedDividendRescaled, R(DecimalUtil::kPowersOfTen[aRescale]));
unsignedDividendRescaled = multiply<R, A>(
unsignedDividendRescaled,
R(DecimalUtil::kPowersOfTen[aRescale]),
overflow);
if (*overflow) {
return R(-1);
}
Expand Down

0 comments on commit b32cc11

Please sign in to comment.