Skip to content

feat(arrow-buffer): add i256::wrapping_div_rem and i256::checked_div_rem - #11425

Merged
alamb merged 3 commits into
apache:mainfrom
mbutrovich:i256-div-rem
Oct 8, 2026
Merged

alamb merged 3 commits into
apache:mainfrom
mbutrovich:i256-div-rem

Conversation

@mbutrovich

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

i256 already computes the quotient and remainder together in a private div_rem, but the public API only exposes them separately through wrapping_div, checked_div, wrapping_rem and checked_rem. A caller that needs both runs div_rem_knuth (Knuth's Algorithm D) twice. Comet's div_round_half_up does this for every row of a wide decimal multiply.

What changes are included in this PR?

This PR adds two public methods to i256, named after the existing wrapping_* and checked_* methods.

  • wrapping_div_rem(self, other) -> (Self, Self) returns (i256::MIN, 0) for i256::MIN / -1 and panics on a zero divisor, the same as wrapping_div and wrapping_rem.
  • checked_div_rem(self, other) -> Option<(Self, Self)> returns None for a zero divisor or i256::MIN / -1.

Both call the private div_rem, so its error type stays private.

Are these changes tested?

Yes. The tests compare both methods against num_bigint::BigInt, which the existing i256 tests already use as a reference. test_ops now checks them, so they run on the candidate pairs in test_i256 and the random pairs in test_i256_fuzz. A new test, test_div_rem_powers_of_ten, uses divisors 10^k - 1, 10^k and 10^k + 1 for k from 0 to 76, with dividends at the i256 and i128 bounds, around 2^64 and 2^128, and next to the divisor, in every sign combination. Another new test checks that wrapping_div_rem panics on a zero divisor. Each method also has a doctest.

Are there any significant user-facing changes?

The two methods are new public API. Nothing existing changes.

AI Disclosure

I wrote this PR with help from Claude but understand and support the core approach, implementation, and test coverage.

@andygrove andygrove left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mbutrovich, this looks good to me. Both methods are thin wrappers over the existing private div_rem and behave the same as wrapping_div, wrapping_rem, checked_div and checked_rem.

Checked in addition to the tests in the PR:

  • A differential test over 30M random operand pairs matched num_bigint and the existing single-op methods exactly, including MIN / -1, zero divisors and the rare correction step in the long division.
  • The tests catch all 7 deliberately broken versions tried (swapped tuple, floored and Euclidean remainder, wrong overflow result, missing panic).

None of the inline comments are blocking. Some follow-up ideas for code outside this diff:

  1. test_i256_fuzz never generates negative operands. It picks the number of random bytes with rng.random_range(0..32) (mod.rs), so byte 31, which holds the sign, is always zero and every operand is below 2^248. The fuzz pairs therefore never reach the sign handling in div_rem, and versions with a floored or Euclidean remainder pass it. Using 0..=32 and randomly negating the operands would fix that.
  2. divide_and_round in arrow-arith could be the first caller in this repo. It follows the same pattern as Comet's div_round_half_up: it calls div_wrapping and mod_wrapping separately and recomputes half = div / 2 for every row (arithmetic.rs). It's private and only used with Decimal256Type, so it could take i256 and call wrapping_div_rem. In a quick benchmark (arm64, 8192 rows, divisors from 10^10 to 10^54) that was 1.6–1.8x faster, and 2.0–2.2x with half computed once outside the loop, with identical output.
  3. Generic decimal code can't reach the fused method. ArrowNativeTypeOp has no fused div/rem, so make_downscaler (decimal.rs) and the overflow fallback scaled_div (numeric.rs) still divide twice per value. A defaulted trait method overridden for i256 would cover both, and since ArrowNativeType is sealed it wouldn't break downstream code. The divisor trait planned in #11421 would cover make_downscaler but not scaled_div, whose divisor changes per row.
  4. A benchmark would show the gain. The existing i256_div_rem benches (i256.rs) only call wrapping_div. In a quick out-of-tree benchmark the fused call was about 1.85x faster than separate wrapping_div and wrapping_rem calls, but only 5–10% faster than computing r = n - q * d from the quotient.
  5. div_rem itself has room to speed up. An i128 fast path, used when both operands fit, was 2.3–3.4x faster on such operands in a quick test. Separately, bits, add_assign and sub_assign in div.rs (L51, L213-L221) aren't #[inline], so crates built without LTO make out-of-line calls on every division (about 20% slower per call when the divisor fits in a u64).

Comment thread arrow-buffer/src/bigint/mod.rs Resolved
Comment thread arrow-buffer/src/bigint/mod.rs Resolved
Comment thread arrow-buffer/src/bigint/mod.rs Resolved
Comment thread arrow-buffer/src/bigint/mod.rs Resolved
@mbutrovich

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @andygrove.

test_i256_fuzz never generates negative operands.

I filed #11452 for this.

divide_and_round in arrow-arith could be the first caller in this repo.

I added multiply_fixed_point benchmarks to #11427, and I filed #11453 for the change itself, which depends on this PR.

Generic decimal code can't reach the fused method.

#11426 already benchmarks make_downscaler, and I added div cases to #11427 whose scaled dividend overflows, so they reach scaled_div. I filed #11454 for the trait methods.

A benchmark would show the gain.

The multiply_fixed_point benchmarks in #11427 cover this. They will show the gain once divide_and_round uses wrapping_div_rem.

div_rem itself has room to speed up.

I filed #11451 for the i128 fast path and the missing #[inline] attributes. The Decimal256 cases in #11426 and #11427 can measure both.

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good to me -- thank you @mbutrovich and @andygrove

/// assert_eq!((q, r), (i256::from_i128(-3), i256::from_i128(-1)));
///
/// let (q, r) = i256::MIN.wrapping_div_rem(i256::MINUS_ONE);
/// assert_eq!((q, r), (i256::MIN, i256::ZERO));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@alamb
alamb added this pull request to the merge queue Oct 8, 2026
Merged via the queue into apache:main with commit 66dd257 Oct 8, 2026
34 checks passed
@Jefffrey Jefffrey added the enhancement New feature/addition label Oct 9, 2026
rluvaton pushed a commit to rluvaton/arrow-rs that referenced this pull request Oct 14, 2026
…che#11526)

# Which issue does this PR close?

- Closes apache#11453.
- Part of apache#11421.

# Rationale for this change

See apache#11453.

# What changes are included in this PR?

`divide_and_round` takes the divisor and returns a closure that computes
`half` and `half_neg` once and divides each row with
`i256::wrapping_div_rem` from apache#11425. `multiply_fixed_point` and
`multiply_fixed_point_checked` build the closure before calling `binary`
and `try_binary`. The results don't change.

# Are these changes tested?

`test_decimal_multiply_fixed_point_rounding` in
`arrow-arith/src/arithmetic.rs` covers rounding of negative products,
ties and both null paths, which the existing tests of
`multiply_fixed_point` and `multiply_fixed_point_checked` don't reach.
It passes on `main` and with this change.

The benchmark bot ran the `decimal128_multiply_fixed_point` cases of the
`decimal_division` benchmark from apache#11427 on
[x86_64](apache#11526 (comment))
(Xeon Platinum 8581C) and
[arm64](apache#11526 (comment))
(Neoverse-V2).

<img width="1600" height="740" alt="multiply-fixed-point-bot"
src="https://github.com/user-attachments/assets/cca8f76e-27c3-4427-8c41-859cd635c03b"
/>

<details><summary>Numbers behind the chart</summary>

In us per 1024 values:

| Case | x86_64: `main` | This PR | arm64: `main` | This PR |
|---|---|---|---|---|
| 15 digits, scale 10 to scale 6 | 45.2 | 16.4 | 73.2 | 29.8 |
| 24 digits, scale 10 to scale 6 | 44.7 | 15.3 | 104.6 | 45.0 |
| 21 digits, scale 20 to scale 6 | 84.1 | 37.0 | 96.2 | 40.4 |

</details>

<details><summary>Apple M5 Max</summary>

With rustc 1.99.0, in us per 1024 values:

| Case | `main` | This PR |
|---|---|---|
| 15 digits, scale 10 to scale 6 | 43.6 | 19.1 |
| 24 digits, scale 10 to scale 6 | 61.1 | 29.4 |
| 21 digits, scale 20 to scale 6 | 53.0 | 23.5 |

</details>

# Are there any significant user-facing changes?

No.

## AI Disclosure

I wrote this PR with help from Claude but understand and support the
core approach, implementation, and test coverage.

Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
etseidl pushed a commit to HippoBaro/arrow-rs that referenced this pull request Oct 15, 2026
…rrowNativeTypeOp` (apache#11528)

# Which issue does this PR close?

- Closes apache#11454.
- Part of apache#11421.

# Rationale for this change

See apache#11454.

# What changes are included in this PR?

`ArrowNativeTypeOp` gains `div_rem_wrapping` and `div_rem_checked`,
which return `(quotient, remainder)`. Their default implementations call
`div_*` and `mod_*`. `i256` overrides them with `i256::wrapping_div_rem`
and `i256::checked_div_rem` from apache#11425, and `div_rem_checked` returns
the same errors as `div_checked`. `native_type_op!` takes optional
trailing items so the `i256` impl can carry the overrides.

The names follow the `*_wrapping` and `*_checked` suffixes of the other
`ArrowNativeTypeOp` methods. `checked_div_rem` would share a name with
`i256::checked_div_rem` but return `Result` instead of `Option`.

`make_downscaler` and `scaled_div` call the new methods.
`ArrowNativeType` is sealed, so adding trait methods with defaults
doesn't break downstream code.

# Are these changes tested?

`test_i256_div_rem` and `test_i256_div_rem_wrapping_zero_panics` in
`arrow-array/src/arithmetic.rs` check the `i256` overrides against
`div_*` and `mod_*`, including the errors. The existing tests cover both
callers with `Decimal256` and negative values, such as
`test_cast_decimal_to_decimal_round` and
`test_decimal256_div_wide_intermediate`.

The benchmark bot ran the `Decimal256` cases of `decimal_downscale` in
the `cast_decimal` benchmark from apache#11426 on
[x86_64](apache#11528 (comment))
and
[arm64](apache#11528 (comment)),
and `decimal256_scalar/div_72_digits_by_4_digits` in the
`decimal_division` benchmark from apache#11427, which reaches `scaled_div`, on
[x86_64](apache#11528 (comment))
and
[arm64](apache#11528 (comment)).
The runners are a Xeon Platinum 8581C and a Neoverse-V2.

<img width="1600" height="1124" alt="div-rem-bot"
src="https://github.com/user-attachments/assets/e2d02705-8357-47b0-b473-447b8910eee2"
/>

<details><summary>Numbers behind the chart</summary>

In us with no nulls, per 8192 values for the casts and per 1024 values
for the division:

| Case | x86_64: `main` | This PR | arm64: `main` | This PR |
|---|---|---|---|---|
| `Decimal256` (76, 10) to (76, 2), 38 digits | 260.7 | 172.0 | 467.7 |
265.5 |
| `Decimal256` (76, 10) to (76, 2), 60 digits | 261.1 | 167.4 | 751.5 |
422.4 |
| `Decimal256` (41, 20) to `Decimal128` (38, 6), 30 digits | 278.8 |
174.6 | 499.9 | 291.3 |
| `Decimal256` (76, 20) to `Decimal128` (38, 6), 48 digits, fallible |
280.7 | 211.1 | 780.7 | 443.1 |
| `Decimal256` (76, 40) to `Decimal128` (38, 6), 42 digits, fallible |
582.3 | 340.9 | 702.5 | 390.4 |
| `Decimal256` 72 digits by 4 digits | 405.8 | 380.7 | 550.3 | 508.5 |

</details>

The cases with nulls and the strict casts changed by about the same
amount. Most of the division case's time goes to the per-digit loop in
`scaled_div` and to the error that apache#11479 stops building.

<details><summary>Apple M5 Max</summary>

With rustc 1.99.0, in us per 8192 values with no nulls:

| Case | `main` | This PR |
|---|---|---|
| `Decimal256` (76, 10) to (76, 2), 38 digits | 178.9 | 104.4 |
| `Decimal256` (76, 10) to (76, 2), 60 digits | 272.1 | 154.0 |
| `Decimal256` (41, 20) to `Decimal128` (38, 6), 30 digits | 263.0 |
153.4 |
| `Decimal256` (76, 20) to `Decimal128` (38, 6), 48 digits, fallible |
460.4 | 294.9 |
| `Decimal256` (76, 40) to `Decimal128` (38, 6), 42 digits, fallible |
380.5 | 227.7 |

`Decimal128` keeps the default methods, and its cases changed by 3% or
less, within the difference between repeated runs. The division case
went from 295 to 284 us per 1024 values, the mean of two alternating
runs each.

</details>

# Are there any significant user-facing changes?

`ArrowNativeTypeOp` has two new methods with default implementations.

## AI Disclosure

I wrote this PR with help from Claude but understand and support the
core approach, implementation, and test coverage.
@mbutrovich
mbutrovich deleted the i256-div-rem branch November 4, 2026 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arrow Changes to the arrow crate arrow-buffer enhancement New feature/addition

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants