Skip to content

Integer.sqrt: Karatsuba square root; String#hash: SipHash-1-3 for long ASCII strings - #202

Merged
Largo merged 2 commits into
masterfrom
claude/issue-89-sqrt-hash
Nov 11, 2026
Merged

Largo merged 2 commits into
masterfrom
claude/issue-89-sqrt-hash

Conversation

@Largo

@Largo Largo commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Part of #89: the Integer.sqrt on large Integers item and the String#hash on long strings item.

1. Integer.sqrt: Karatsuba square root, and no BigInteger at all below 2**106

#190 started Newton's iteration from the double's square root. That still meant several full-width BigInteger divisions per call, and on .NET 11.0.0 BigInteger division is 3–6× slower than on .NET 10.

  • 262 .. 2106: the root fits in 53 bits. The double's root of the value (read as a UInt128) is off by a few units at most, and it is corrected to the exact floor with UInt128 squares. No BigInteger arithmetic.
  • Above 2106:** Integer.SqrtRem, Zimmermann's Karatsuba square root with remainder. This is Brent and Zimmermann, Modern Computer Arithmetic, algorithm 1.12, the same algorithm as GMP's mpz_sqrtrem.
    • Write n = A·B² + a1·B + a0 with B = 2^k.
    • Recursively take the root s' and remainder r' of A.
    • One division, (r'·B + a1) / 2s', gives the next k bits q of the root. One squaring of q gives the remainder.
    • k = (bits + 1) / 4, so A ≥ B²/4. That normalisation is what limits the correction to one step.
    • Each level divides numbers half the size of the level above. The whole costs about one division of n's size by half of it, where Newton made several.
  • SqrtSeed (#89: Integer#[], Integer.sqrt, pow(b, m), Kernel#Integer parsing and tail calls, Data.define #190) and its test are gone. Nothing else used it.

2. String#hash: SipHash-1-3 for long ASCII strings, and one-pass UTF-8 decoding

  • Long (128+) ASCII strings hashed their bytes with Marvin (#89: share suffix and middle slices of long strings; hash long ASCII strings as bytes #195). They now use SipHash-1-3 under a random 128-bit key drawn once per process (RandomNumberGenerator). This is CRuby's string hash, and Python's and Rust's.
    • It is ~1.5× as fast per byte as Marvin. Steady state, standalone C#: 1 MB in 0.24 ms against 0.38 ms.
    • It is as hard to flood without the key.
    • Short strings and non-ASCII characters still use String.GetHashCode (Marvin), so short Hash keys are unchanged.
    • Side effect: #89: share suffix and middle slices of long strings; hash long ASCII strings as bytes #195 noted an even-length ASCII string that collided, whatever the seed, with the UTF-16 string its bytes spell. That pair no longer collides, because the two are now hashed by different keyed functions.
  • Non-ASCII UTF-8 held as bytes: the bytes were validated three times before the characters were hashed (EscapingEncoding's count and its decode each check again).
    • The hash now decodes once with Utf8.ToUtf16. Only invalid bytes fall back to the escaping decoder.
    • The hash is the same, because the escaping decoder already hands valid UTF-8 to the standard decoder.
    • ("é" * 500).hash takes about half as long as before (it is held as bytes).
  • Considered and not done:
    • XxHash3: not in the box (a NuGet dependency), and it makes no claim to resist hash flooding.
    • SipHash over the UTF-8 bytes of every long string: it would help non-ASCII strings held as bytes, but strings held as characters would then pay a transcode on every #hash. .NET validates non-ASCII UTF-8 at ~0.6 ns/byte, so a byte-held one could not get much below ~3× CRuby anyway.

Measurements

Release build. Thread CPU time, taskset to one core, ≥0.6 s warm-up per case, best of 5. Three interleaved rounds per build: CRuby, then master and branch for net10.0, then the same for net11.0. The table shows the range of the three bests, in ns unless marked µs.

The box was heavily loaded by other jobs during these runs (load average 7–25), so the spread is wide. Read the low ends.

case CRuby 4.0.9 master net10.0 branch net10.0 master net11.0 branch net11.0
Integer.sqrt(2**70) 263–526 702–1380 201–270 1268–1368 178–268
Integer.sqrt(2**100 + c) 474–742 666–1130 203–358 949–1219 186–276
Integer.sqrt(2**2000 + 1) 5.1–8.7 µs 15–16 µs 7.2–8.4 µs 9.6–15 µs 4.6–9.1 µs
Integer.sqrt 20k bits 61–91 µs 1312–1452 µs 149–188 µs 517–556 µs 337–414 µs
Integer.sqrt 100k bits 432–605 µs 14.1–17.6 ms 1.3–4.2 ms 8.5–9.9 ms 3.1–5.3 ms
hash 1 KB ASCII 299–455 699–798 444–608 1020–1104 411–721
hash 1 KB ASCII, BINARY 309–485 665–746 399–600 769–794 362–512
hash 1 KB UTF-8 ("é" * 500) 339–430 2264–3026 1118–1584 1862–2319 961–1542
hash 100 KB ASCII 25–41 µs 48–52 µs 30–37 µs 44–46 µs 31–39 µs
hash 100 KB ASCII, BINARY 26–42 µs 48–57 µs 30–39 µs 45–48 µs 31–36 µs
hash 1 MB ASCII 294–389 µs 531–689 µs 354–434 µs 488–508 µs 323–404 µs

CRuby's figures include ~14 ns of while loop, IronRuby's ~2 ns.

Short keys were measured separately, in four interleaved rounds on another core. They are unchanged:

case master net10.0 branch net10.0 master net11.0 branch net11.0
"abcdefghijklmnop".hash 77–112 81–112 70–113 72–110
40-byte key .hash 74–102 78–100 70–97 69–97
h["key_500"] (1000 keys) 84–148 54–138 105–132 99–129

On a quiet run, sqrt by size (steady state, net10.0 / net11.0, ns): 120 bits 734 / 767, 250 bits 1447 / 1574, 1000 bits 2569 / 2843, 2000 bits 4090 / 4201, 8000 bits 9604 / 7478. CRuby on the same run: 806, 1555, 3932, 6549, 24406.

What is left above ~10k bits is .NET's BigInteger multiply and divide against GMP, with net11.0's slower division on top.

Verification

  • sqrt against CRuby 4.0.9: 1,738 values up to 100k bits give byte-identical output on net10.0 and net11.0. The values include random values at every size from 1 to 400 bits, 2^b ± 1 around 62/64/106/128 bits, and k², k² ± 1, k² + 2k and (k+1)² − 1 at 73 sizes up to 100k bits.
  • eql? ⇒ same hash:
    • 22 sample strings × every Encoding.list entry × 8 ways to hold them, plus CLR strings: 16,102 strings and 2,440,776 eql? pairs, with 0 hash mismatches on net10.0 and on net11.0.
    • The samples cover empty, short, 127/128/129, odd and even lengths, é, CJK, astral characters, a BOM, invalid bytes and BINARY with high bytes.
    • The 8 ways are force_encoding, dup, an offset slice, a byteslice from an offset, switched to characters, switched there and back, encode and encode switched to characters.
    • The same script on CRuby: 2,430,806 pairs, 0 mismatches.
  • IronRuby.Tests (Debug), full suite: PASSED on net10.0 and net11.0. New:
    • Integer_SqrtRem1: s·s + r == n and 0 ≤ r ≤ 2s for 1–600 bits (random values, powers of two ± 1, k², k² ± 1, k² + 2k, k² + 2k + 1) and up to 1M bits. It replaces Integer_SqrtSeedHuge1.
    • MutableString_SipHash1: checks the SipHash-1-3 implementation against a plain one with the round counts as parameters. That plain one reproduces the SipHash paper's 2-4 test vectors.
    • Integer_SqrtLarge1, MutableString_GetHashCode2/3 unchanged and passing.
  • ruby/spec at CI's refs (SPEC_REF dda28d04), Release, master vs branch, net10.0 and net11.0: core/integer 598 examples, core/string 3963, core/hash 562, core/symbol 270. The failing examples are identical on both builds: only the known try_convert "into"/"to" wording errors (2 in integer, 1 in string, 1 in hash).
  • No [RubyMethod] signature changed, so the initializers need no regeneration.

Review

I ran the repo's review skill as an independent pass. It found no Blockers, no Should-fixes and no Notes. Beyond the checks above, it compared sqrt against CRuby on 26,255 more values (every size 60–1200 bits, with s² neighbours) on both runtimes. It also checked eql?/hash on CLR strings, BOMs, astral characters, offset slices and invalid UTF-8.

One problem came up along the way, before the PR was opened: my edits had turned six CRLF files into LF. I restored CRLF, so the diff is only the real change (~270 lines).

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; no actionable issues were found.

Summary

This PR speeds up large integer square roots and string hashes.

  • Integer.sqrt uses a small-number fast path and recursive large-number roots.
  • Long ASCII strings now use a keyed hash for their bytes.
  • Valid UTF-8 strings held as bytes hash after one decode.

No actionable issues were found. This review checked source code and existing tests; it did not run the test suite.

Reviews (1) · Last reviewed commit: "String#hash: SipHash-1-3 for long ASCII ..." · Reviewed by Greptile

Summary by CodeRabbit

  • Performance
    • Improved integer square-root calculations across small and very large values.
    • Improved hashing performance for eligible ASCII and valid UTF-8 strings.
  • Bug Fixes
    • Integer square-root results now include a verified remainder, improving accuracy across a wider range of input sizes.
    • String hashing uses SipHash-1-3 for qualifying ASCII strings while preserving fallback handling for invalid UTF-8.

Largo and others added 2 commits November 11, 2026 11:43
…2**106

Newton's iteration from the double's root (#190) made several full-width
BigInteger divisions per call, and .NET 11's division is slow.

- 2**62..2**106: the double's root of the value as a UInt128 is off by a
  few units at most; it is corrected to the exact floor with UInt128
  squares. No BigInteger division at all.
- Above: Zimmermann's Karatsuba square root with remainder (Brent and
  Zimmermann, Modern Computer Arithmetic, algorithm 1.12; GMP's
  mpz_sqrtrem). Each level takes the root of the top half and gets the
  next k bits in one division of half the size, and the remainder in one
  squaring; the split keeps the top part >= B**2/4, so at most one
  correction follows.

SqrtSeed and its test go; Integer_SqrtRem1 checks s*s + r == n and
0 <= r <= 2s from 1 to 600 bits (random, k*k and its neighbours, powers
of two) and up to a million bits.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…UTF-8 bytes

- Long (128+) ASCII strings hashed their bytes with Marvin (#195). They
  now use SipHash-1-3 under a random 128-bit key drawn once per process,
  as CRuby does: about 1.5 times as fast per byte, and as hard to flood
  without the key. Short strings and non-ASCII characters keep
  String.GetHashCode (Marvin), so short Hash keys are unchanged. The
  even-length ASCII string that collided with the UTF-16 string its
  bytes spell, whatever the seed, no longer does: the two hashes are now
  different keyed functions.
- A non-ASCII UTF-8 string held as bytes validated them three times
  (the escaping encoding's count and decode each check them again) before
  hashing the characters. It now decodes once with Utf8.ToUtf16 and falls
  back to the escaping decoder only for invalid bytes. Same hash, since
  the escaping decoder hands valid UTF-8 to the standard one.

MutableString_SipHash1 checks the implementation against a plain one with
the round counts as parameters, which gives the SipHash paper's 2-4
vectors.

Part of #89.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The integer square-root implementation now uses size-based paths and can return both the floor root and remainder. MutableString hashing adds SipHash-1-3 for qualifying ASCII bytes and a valid UTF-8 path for non-ASCII bytes. Tests cover both changes.

Changes: Integer square root

Layer / File(s) Summary
Size-based square-root implementation
Src/Libraries/Builtins/Integer.cs
Integer.sqrt selects LongSqrt, SmallSqrt, or SqrtRem based on input size. SqrtRem recursively computes a root and remainder for larger inputs; SmallSqrt corrects its estimate to the exact floor.
Square-root invariant tests
Src/IronRuby.Tests/Runtime/IntegerTests.cs, Src/IronRuby.Tests/RubyTests.cs
Integer_SqrtRem1 checks the root-and-remainder invariant across boundary values, random values, and selected large inputs. The test registration replaces the previous SqrtSeed test registration.

MutableString hashing

Layer / File(s) Summary
SipHash-1-3 implementation
Src/Ruby/Builtins/SipHash.cs
Adds keyed SipHash-1-3 hashing, process-level random keys, and a folded 32-bit hash entry point.
MutableString hashing paths and tests
Src/Ruby/Builtins/MutableString.Content.cs, Src/Ruby/Builtins/MutableString.BinaryContent.cs, Src/Ruby/Builtins/MutableString.cs, Src/IronRuby.Tests/Runtime/MutableStringTests.cs, Src/IronRuby.Tests/RubyTests.cs
ASCII byte hashing uses SipHash. Binary content attempts to hash decoded characters for valid non-ASCII UTF-8 and uses the existing fallback for invalid UTF-8. Tests compare SipHash-1-3 results with a reference implementation.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

Possibly related PRs

  • Largo/ironruby#95: This PR replaces the earlier Integer.sqrt implementation with size-based square-root paths and SqrtRem.
  • Largo/ironruby#186: Both PRs change MutableString hash computation and add hash-related tests.

Suggested reviewers: claude

Merge Risk: Minimal · up to 9ebbd

This change speeds up large-integer square roots and adds keyed hashing for long ASCII strings. The supplied evidence shows no concrete defect, and tests cover the main invariants, so no merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies both primary changes: the Karatsuba-based Integer.sqrt implementation and SipHash-1-3 for long ASCII strings.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a21b4ad and 9ebbdd9.

Files selected for processing: 8

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/IntegerTests.cs
  • Src/IronRuby.Tests/Runtime/MutableStringTests.cs
  • Src/Libraries/Builtins/Integer.cs
  • Src/Ruby/Builtins/MutableString.BinaryContent.cs
  • Src/Ruby/Builtins/MutableString.Content.cs
  • Src/Ruby/Builtins/MutableString.cs
  • Src/Ruby/Builtins/SipHash.cs

Included review availability: This review used your included allowance. 0 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

@Largo
Largo merged commit a8275a4 into master Nov 11, 2026
7 checks passed
Largo added a commit that referenced this pull request Nov 11, 2026
Brings in #202 (Integer.sqrt, String#hash) and #204 (exception fixes),
which change ruby4.rb and the code the startup library compiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

1 participant