cloud-fan commented on code in PR #55476:
URL: https://github.com/apache/spark/pull/55476#discussion_r3123990197
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala:
##########
@@ -5238,34 +5241,42 @@ case class ArrayInsert(
} else {
val pos = posExpr.value
val baseOffset = if (legacyNegativeIndex) 1 else 0
+ // Widen `pos` arithmetic to long so that `Int.MIN_VALUE` doesn't
silently overflow
+ // (e.g. `Math.abs(Int.MIN_VALUE)` returns `Int.MIN_VALUE`).
+ val posLong = ctx.freshName("posLong")
+ val resLengthLong = ctx.freshName("resLengthLong")
s"""
+ |long $posLong = (long) $pos;
|int $itemInsertionIndex = 0;
|int $resLength = 0;
|int $adjustedAllocIdx = 0;
|boolean $insertedItemIsNull = ${itemExpr.isNull};
|
- |if ($pos == 0) {
+ |if ($posLong == 0L) {
| throw
QueryExecutionErrors.invalidIndexOfZeroError($errorContext);
|}
|
- |if ($pos < 0 && (java.lang.Math.abs($pos) > $arr.numElements())) {
+ |if ($posLong < 0L && (-$posLong > $arr.numElements())) {
|
- | $resLength = java.lang.Math.abs($pos) + $baseOffset;
- | if ($resLength > ${ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH}) {
+ | long $resLengthLong = -$posLong + ${baseOffset}L;
+ | if ($resLengthLong >
${ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH}) {
| throw
QueryExecutionErrors.arrayFunctionWithElementsExceedLimitError(
- | "$prettyName", $resLength);
+ | "$prettyName", $resLengthLong);
| }
+ | $resLength = (int) $resLengthLong;
|
| $allocation
| for (int $i = 0; $i < $arr.numElements(); $i ++) {
- | $adjustedAllocIdx = $i + $baseOffset + java.lang.Math.abs($pos
+ $arr.numElements());
+ | $adjustedAllocIdx =
+ | $i + $baseOffset + (int) java.lang.Math.abs($posLong +
$arr.numElements());
| $assignment
| }
| ${CodeGenerator.setArrayElement(
values, elementType, itemInsertionIndex, item,
Some(insertedItemIsNull))}
|
| for (int $j = ${if (legacyNegativeIndex) 0 else 1} + $pos +
$arr.numElements(); $j < 0; $j ++) {
Review Comment:
Nit: the loop init here still uses `$pos` while the `Math.abs($posLong +
...)` one line below uses `$posLong`. It's safe — by the time this loop runs,
the `resLengthLong` check has forced `posLong > Int.MinValue`, and `$pos +
$arr.numElements()` with `$pos < 0` and `$arr.numElements() >= 0` can't
overflow — but the mixed int/long usage within the same branch is a bit
surprising. Worth widening to `$posLong` here too for consistency?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]