Skip to content

Hash#dup, #merge, #replace, Hash[]: copy entries without re-hashing keys - #83

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

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

Conversation

@Largo

@Largo Largo commented Nov 3, 2026 •

Copy link
Copy Markdown
Owner

IDictionaryOps.ReplaceData (Src/Libraries/Extensions/IDictionaryOps.cs) has been unchanged since the 2016 import. It is what Hash#dup, #merge, #replace, Hash[hash] and initialize_copy copy with. It cleared the destination and inserted every pair again through IDictionary, so every key was hashed again. For a String or any other object key that is a #hash call. #dup and #merge even copy twice: once in initialize_copy, then again in Duplicate.

Change

Hash stores each entry's hash code. When source and destination use the same comparer, those codes are valid in the destination too.

The new Hash.TryCopyEntriesFrom in Src/Ruby/Builtins/Hash.Storage.cs copies the live entries in one block, skipping tombstones. It then rebuilds the buckets from the stored codes, with no comparer call at all. ReplaceData uses it when both sides are a Hash.

The old path still handles these cases:

  • Different comparers, e.g. a #replace between hashes that differ in compare_by_identity.
  • A hash copied onto itself.
  • Anything that isn't a Hash.

A copy into a hash that is being iterated raises the same error the first insert would have.

Numbers

10,000 entries, 20 copies, best of 3, each case in its own process. Release, net8.0; CRuby 3.3 for comparison.

before after CRuby
Hash#dup, Integer keys 18.1 ms 3.9 ms 1.2 ms
Hash#dup, String keys 28.9 ms 2.1 ms 0.9 ms
Hash#merge({}) 15.2 ms 1.9 ms 0.8 ms
{}.replace(h) 26.8 ms 2.3 ms 1.1 ms
Hash[h] 24.2 ms 2.2 ms 1.0 ms

Small hashes and Hash#== are unchanged.

Testing (Linux, net8.0, Release)

  • Differential check against CRuby (26 cases; inspect format normalized, since local CRuby is 3.3): identical output. It covers:

    • nil keys and tombstones after deletes;
    • mutating the copy independently of the original;
    • compare_by_identity in both directions of #replace;
    • default values and procs, and subclasses;
    • frozen String keys staying the same objects;
    • #replace during iteration, onto itself and on a frozen hash;
    • #rehash after a key was mutated.
  • Util/run-tests.sh: PASSED, 0 failure lines.

  • ruby/spec, each suite compared with the build without this change:

    Suites Examples Failures Errors
    core/{hash,env,struct} 925 0 0
    language, core/{kernel,enumerable,array} 8,599 1 2
    core/{marshal,objectspace,set}, library/openstruct 811 0 20

    The failures and errors are the same without the change.


Generated by Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Replacing data between compatible hashes now preserves the source entries’ insertion order. Existing safeguards remain in place when a hash is being iterated, and replacements with incompatible hashes continue to use the established fallback behavior.

IDictionaryOps.ReplaceData, unchanged since the 2016 import, cleared
the destination and inserted every pair through IDictionary again, so
each key was hashed again - a #hash call for a String or any object key
- and Hash#dup and #merge copy twice (initialize_copy, then Duplicate).

Hash stores each entry's hash code. When source and destination use
the same comparer those codes are valid in the destination too, so the
new Hash.TryCopyEntriesFrom copies the live entries in one block
(skipping tombstones) and re-chains the buckets from the stored codes:
no comparer call at all. Different comparers, or a hash copied onto
itself, take the old path. A copy into a hash that is being iterated
raises what the first insert would have.

10,000 entries, 20 copies, best of 3 (Release, net8.0; CRuby 3.3):
  Hash#dup, Integer keys        18.1 -> 3.9 ms   (1.2)
  Hash#dup, String keys         28.9 -> 2.1 ms   (0.9)
  Hash#merge({})                15.2 -> 1.9 ms   (0.8)
  {}.replace(h)                 26.8 -> 2.3 ms   (1.1)
  Hash[h]                       24.2 -> 2.2 ms   (1.0)
Small hashes and Hash#== are unchanged.

Checked against CRuby (inspect format normalized): nil keys,
tombstones after deletes, independent mutation of the copy,
compare_by_identity in both directions of #replace, default values and
procs, subclasses, frozen String keys staying the same objects, replace
during iteration, onto itself and frozen, rehash after a key mutated.

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

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Walkthrough

Hash.TryCopyEntriesFrom copies live entries when the source and destination use the same comparer instance. ReplaceData uses this operation for Hash instances and keeps the existing clear-and-reinsert fallback.

Changes: Hash replacement

Layer / File(s) Summary
Copy Hash entries and integrate with ReplaceData
Src/Ruby/Builtins/Hash.Storage.cs, Src/Libraries/Extensions/IDictionaryOps.cs
TryCopyEntriesFrom copies live entries in insertion order, rebuilds buckets, and updates the destination’s version and mutation stamp. ReplaceData uses this method when both dictionaries are Hash instances and falls back to clearing and reinserting when the method does not succeed.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Possibly related PRs

  • Largo/ironruby#22: Adds the Hash entry storage structures that TryCopyEntriesFrom uses, including stored hash codes and tombstones.

Suggested reviewers: claude

Merge Risk: Minimal · up to ad1d3

No PR-introduced issue remains identified; the change is mergeable after normal checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the primary change: Hash#dup, #merge, #replace and Hash[] now copy entries without re-hashing keys. The summary shows Hash.TryCopyEntriesFrom reuses stored hash codes and is wired into…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
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.
Full details: Title check

Explanation

The title names the primary change: Hash#dup, #merge, #replace and Hash[] now copy entries without re-hashing keys. The summary shows Hash.TryCopyEntriesFrom reuses stored hash codes and is wired into IDictionaryOps.ReplaceData, which serves these operations. The title is specific and matches the changeset's main purpose.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 2 functions across 2 files.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • 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
Recent review info
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: bdb07cc6-62ff-47db-8871-3c48bea87455
Commits

Reviewing files that changed from the base of the PR and between 12015af and ad1d307.

Files selected for processing: 2
  • Src/Libraries/Extensions/IDictionaryOps.cs
  • Src/Ruby/Builtins/Hash.Storage.cs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@Largo
Largo merged commit 9312954 into master Nov 3, 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