Skip to content

Numerics: Float->Integer and unpack('w') without exceptions, fast to_s(radix), Int64 shifts; Integers in the Int64 range as longs - #86

Merged
Largo merged 1 commit into
masterfrom
ccr-4d94625d-0splsp-a2
Nov 4, 2026
Merged

Largo merged 1 commit into
masterfrom
ccr-4d94625d-0splsp-a2

Conversation

@Largo

@Largo Largo commented Nov 4, 2026

Copy link
Copy Markdown
Owner

This PR speeds up four slow paths in code unchanged since the 2016 import, and fixes a bug where an Integer between 231 and 263 could be missed as a Hash key.

Bug: Integers in the long range must be longs

Since 26c8e91, an Integer from 231 up to 263 is meant to be stored as a long. Three places produced a BigInteger instead, and the Hash key comparer does not match a BigInteger against a long:

  • Float → Integer conversion;
  • integer literals (PrismAstBridge.BigIntegerLiteral; this adds Literal.Long);
  • NumericRounding.Normalize, used for rounding to negative digits.
{3 * 1_000_000_000 => 1}[3_000_000_000]   # CRuby 1, IronRuby nil
{10**12 => 1}[1e12.floor]                 # CRuby 1, IronRuby nil

All three now go through Protocols.Normalize. About 25 ways of producing such values were checked; all now give a long and are found as Hash keys. The literal and NumericRounding parts are in 2026 files, but they are the same bug.

Speed

  1. ClrFloat.CastToInteger called Convert.ToInt32 and caught OverflowException, so converting any Float outside the Int32 range threw an exception (~10 µs). This sits behind Float#to_i/floor/ceil/round/truncate, Integer(float), Float#to_r and #rationalize. It now uses range checks and returns int, long or BigInteger.
  2. RubyEncoder.ReadBer (unpack('w')) found the end of the data by catching IndexOutOfRangeException, at least once per unpack("w*"). It now checks the byte count.
  3. Integer#to_s(radix) used DLR MathUtils.ToString, which divides the whole number once per digit (quadratic), and then lowercased the result. The new ToRadixString works in three ways:
    • long arithmetic when the value fits in a long;
    • reading the bits directly when the radix is a power of two;
    • otherwise, one BigInteger division per long-sized chunk of digits.
  4. <<, >>, ~ on Int64 receivers went through BigInteger and back. This adds long overloads in ClrInteger.Int64.cs; Initializers.Generated.cs was regenerated with ClassInitGenerator, and its only diff is those three entries. An Int32 << that overflows now stays in long arithmetic when the result fits.

ns per operation, best of 3, interleaved runs, Release, net8.0:

before after CRuby 3.3
1e15.floor 10,365 50 33
Float#to_r 13,658 2,264 (the rest is the prelude) 253
1e20.round(-3) 11,395 322 456
unpack("w*"), 5 ints 9,172 242 374
i.to_s(2) 744 203 145
(2**100).to_s(16) 1,449 196 178
(2**100).to_s(7) 1,965 585 304
(3**2000).to_s(2) 2,047,798 9,170 8,137
(3**2000).to_s(3) 1,290,481 75,727 5,487
long >> 3 153 40 32
~long 124 40 24

Testing (Linux, net8.0, Release)

  • Differential checks against CRuby. Output is identical for all of these:
    • to_s(2..36) and inspect of about 830 values: the Int32, Int64, 263 and 264 boundaries, plus random values up to 400 bits, in both signs.
    • to_i, floor, ceil, round and truncate (also with digits and half:), divmod, Integer(), to_r, rationalize and Hash lookups for about 230 floats, plus the NaN/Infinity errors.
    • pack/unpack('w'), including truncated data.
    • <<, >> and ~ for about 630 values × 40 shift widths, with Float, to_int and invalid arguments: 53,836 lines.
  • Shifts by Int32.MinValue and 264** give the same results as before the change.
  • New IronRuby.Tests:
    • Integer_Normalization1: its script's output differs from CRuby on the old build.
    • Integer_ToStringRadix1, Pack_BerTruncated1, Integer_Int64Shifts1.
  • Util/run-tests.sh: PASSED, 0 failure lines.
  • ruby/spec: 5,904 examples, 0 failures and 15 errors, identical to the build without the change. The suites were core/{integer,float,numeric,range,hash}, array/pack, string/{unpack,unpack1}, kernel/{Integer,Float} and language/numbers.

Generated by Claude Code

…(radix), Int64 shifts; normalize Integers in the Int64 range

All slow paths are in code unchanged since the 2016 import.

Speed:
- ClrFloat.CastToInteger (behind Float#to_i/floor/ceil/round/truncate,
  Integer(float), Float#to_r, #rationalize, rounding with digits) called
  Convert.ToInt32 and caught its OverflowException, so every Float outside
  the Int32 range cost a thrown exception (~10 us). It now range-checks.
- RubyEncoder.ReadBer (String#unpack 'w') found the end of the data by
  catching IndexOutOfRangeException - once per unpack('w*') at least.
  It now checks the length.
- Integer#to_s(radix) went through DLR MathUtils.ToString, which divides
  the whole BigInteger by the radix once per digit (quadratic), then
  ToLowerInvariant. Now: Int64 range with machine arithmetic, power-of-two
  radices by reading bits, other radices one division per long-sized chunk.
- Int64 receivers of <<, >>, ~ converted to BigInteger and back; added
  long overloads (Initializers.Generated.cs regenerated), and Int32 << that
  overflows Int32 stays in long arithmetic when it fits.

Bug (regression test Integer_Normalization1, fails on the old code):
Integers in the Int64 range must be longs (commit 26c8e91), but Float
conversions (CastToInteger returned BigInteger past Int32), integer
literals (PrismAstBridge) and NumericRounding.Normalize left BigIntegers,
which the Hash comparer does not match against a long:
  {3 * 1_000_000_000 => 1}[3_000_000_000]   # CRuby 1, IronRuby nil
  {10**12 => 1}[1e12.floor]                 # CRuby 1, IronRuby nil
All three now go through Protocols.Normalize.

Release net8.0, ns/op, min of 3 runs (CRuby 3.3 / before / after):
  1e15.floor             33 / 10365 /   50
  Float#to_r            253 / 13658 / 2264  (rest is the Ruby prelude)
  1.0e20.round(-3)      456 / 11395 /  322
  unpack('w*') 5 ints   374 /  9172 /  242
  i.to_s(2)             145 /   744 /  203
  i.to_s(16)             81 /   315 /  109
  (2**100).to_s(16)     178 /  1449 /  196
  (2**100).to_s(7)      304 /  1965 /  585
  (3**2000).to_s(2)    8137 / 2047798 / 9170
  (3**2000).to_s(3)    5487 / 1290481 / 75727
  (2**40) >> 3           32 /   153 /   40
  ~(2**40)               24 /   124 /   40
  (2**40) << 3           33 /    85 /   49

Testing: differential scripts against CRuby, identical output:
to_s(2..36) and inspect of ~830 values (Int32/Int64/2**63/2**64 boundaries,
random up to 400 bits, both signs); to_i/floor/ceil/round/truncate (also
with -10..2 digits, half:), divmod, Integer(), to_r, rationalize and Hash
lookup of ~230 floats incl. 2**31/2**63 boundaries, NaN/+-Infinity errors;
pack/unpack 'w' incl. truncated data; <<, >>, ~ for ~630 values x 40
shift widths, Float/to_int/invalid arguments (53,836 lines). New tests
Integer_Normalization1, Integer_ToStringRadix1, Pack_BerTruncated1,
Integer_Int64Shifts1. IronRuby.Tests PASSED, 0 FAILED. mspec core/integer,
float, numeric, range, hash, array/pack, string/unpack(1), kernel/Integer,
kernel/Float, language/numbers: 5904 examples, same 15 pre-existing errors
as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KPwZf5xqgL3eZiUCWPfG2b
@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f401bcd5-7d69-4d4c-9db7-eaf3766d852c
Commits

Reviewing files that changed from the base of the PR and between 9312954 and 868e88c.

Files ignored due to path filters: 1
  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 10
  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/IntegerTests.cs
  • Src/Libraries/Builtins/RubyEncoder.cs
  • Src/Libraries/Extensions/ClrBigInteger.cs
  • Src/Libraries/Extensions/ClrFloat.cs
  • Src/Libraries/Extensions/ClrInteger.Int64.cs
  • Src/Libraries/Extensions/ClrInteger.cs
  • Src/Libraries/Extensions/NumericRounding.cs
  • Src/Prism/PrismAstBridge.cs
  • Src/Ruby/Compiler/Ast/Expressions/Literal.cs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@Largo
Largo merged commit 753acb5 into master Nov 4, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants