Skip to content

Commit

Permalink
introduce computeValidSum for spark sql reuse
Browse files Browse the repository at this point in the history
  • Loading branch information
liujiayi771 committed Oct 31, 2023
1 parent 62d8917 commit f5eca90
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
18 changes: 5 additions & 13 deletions velox/functions/lib/aggregates/SumAggregateBase.h
Original file line number Diff line number Diff line change
Expand Up @@ -185,19 +185,11 @@ class DecimalSumAggregate

virtual int128_t computeFinalValue(
functions::aggregate::LongDecimalWithOverflowState* accumulator) final {
// Value is valid if the conditions below are true.
int128_t sum = accumulator->sum;
if ((accumulator->overflow == 1 && accumulator->sum < 0) ||
(accumulator->overflow == -1 && accumulator->sum > 0)) {
sum = static_cast<int128_t>(
DecimalUtil::kOverflowMultiplier * accumulator->overflow +
accumulator->sum);
} else {
VELOX_CHECK(accumulator->overflow == 0, "Decimal overflow");
}

DecimalUtil::valueInRange(sum);
return sum;
auto sum =
DecimalUtil::computeValidSum(accumulator->sum, accumulator->overflow);
VELOX_CHECK(sum.has_value(), "Decimal overflow");
DecimalUtil::valueInRange(sum.value());
return sum.value();
}
};

Expand Down
18 changes: 17 additions & 1 deletion velox/type/DecimalUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,23 @@ class DecimalUtil {
}
}

/// Origins from java side BigInteger#bitLength.
inline static std::optional<int128_t> computeValidSum(
int128_t sum,
int64_t overflow) {
// Value is valid if the conditions below are true.
int128_t validSum = sum;
if ((overflow == 1 && sum < 0) || (overflow == -1 && sum > 0)) {
validSum = static_cast<int128_t>(
DecimalUtil::kOverflowMultiplier * overflow + sum);
} else {
if (overflow != 0) {
return std::nullopt;
}
}
return validSum;
}

/ // Origins from java side BigInteger#bitLength.
///
/// Returns the number of bits in the minimal two's-complement
/// representation of this BigInteger, <em>excluding</em> a sign bit.
Expand Down

0 comments on commit f5eca90

Please sign in to comment.