sin_deep_merge 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 668e1937a83c6eb5dc101ee1412bfc3ccee4a8eae0acda798f524b43b0483539
4
- data.tar.gz: b63c85ff319bee536d2ee92c42bdc30533e67b691db2d67455851ca99bdaed7b
3
+ metadata.gz: 9c0de78531accd5e3c4de48840657ad242cfae56cc25da3af72c2f40f96c613f
4
+ data.tar.gz: 9a2d92dbc4ed62240558fdb49b1941bb8bfe8c882735e9d40058b62d7018a26b
5
5
  SHA512:
6
- metadata.gz: 8f974b808bd991ca5da998e4bc36591a94096d523cf02a7f23ff1a2fd27e645d6e4c8b9889b679b1b6efaf09ad11bc5b38b8181db914e9128d3f04ee73bcea73
7
- data.tar.gz: f29b8af3fbc7df6de7f940a878beecca72af8fca5af239cbb2ef49e9808ea51dc37de0701d2ddb158cfaa7c4ddaf71ce828bf3e6a8bdecc9d87c22139e4b24ff
6
+ metadata.gz: 9115d25940608f6d6a983c3ce023072f25baf3e1e3e880314bd49ac69bd3bbb1c3ac8af025a01cda7db03ac2e6b39da7f68943edcc476af1c6c962ca02c09555
7
+ data.tar.gz: 28ed98467cb848f6e7bbee14da77682e52acbfa081a11993d7bff9a660503cf7d90afe19051833b93e5a97a35812e0c333e75b832ef0ad845dee581542e6c1be
data/CHANGELOG.md ADDED
@@ -0,0 +1,124 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [2.0.0] - 2026-08-10
9
+
10
+ ### Added
11
+
12
+ - Add Ractor support (C, Java)
13
+ - Add `SinDeepMerge::Fallback` and route Hash subclasses that override `merge!` or `update` such as `ActiveSupport::HashWithIndifferentAccess` through it (C, Java)
14
+
15
+ ### Fixed
16
+
17
+ - Merge nested hashes into copies in `deep_merge!` so that a shared or frozen nested hash is never mutated in place (C)
18
+ - Raise `TypeError` for non-Hash argument (C)
19
+ - Raise `SystemStackError` instead of crashing on deeply nested hashes (Java)
20
+ - Prevent crash on repeated stack overflow (C)
21
+ - Fix `ClassCastException` for non-Symbol keys (Java)
22
+ - Align `deep_merge` and `deep_merge!` arity across C and Java
23
+ - Load Java extension without `JRuby::Util.load_ext`
24
+ - Include files under lib in packaged gem
25
+ - Install C extension under `sin_deep_merge` directory
26
+ - Keep stray compiled jar out of packaged gem
27
+
28
+ ### Changed
29
+
30
+ - Optimize block invocation by yielding directly instead of allocating a Proc (C)
31
+ - Skip `initialize_dup` when copying hashes (C)
32
+ - Simplify native extension loading
33
+ - Improve readability of C extension
34
+ - Remove unneeded json gem dependency
35
+ - Minimize gem version constraints
36
+ - Add JRuby build and test script
37
+ - Make test task depend on compile
38
+ - Recompile jar
39
+ - Rework benchmark to compare like for like and report measurement error
40
+ - Add Ractor, Hash subclass and key type test coverage
41
+ - Update Ruby and JRuby versions in CI matrix
42
+ - Verify committed jar matches Java source in CI
43
+ - Require tests to pass before releasing in CI
44
+ - Pin `google-java-format` version and fail on download errors in CI
45
+ - Update `actions/checkout` v6 to v7 in CI
46
+ - Remove assign workflow
47
+ - Update sponsor link to GitHub Sponsors
48
+ - Update README.md
49
+ - Update .gitignore
50
+ - Update .rubocop.yml
51
+
52
+ ## [1.0.2] - 2026-02-22
53
+
54
+ ### Changed
55
+
56
+ - Recompile jar
57
+
58
+ ## [1.0.1] - 2026-02-21
59
+
60
+ ### Fixed
61
+
62
+ - Add frozen check for `deep_merge!` to raise `FrozenError` on frozen Hash (C, Java)
63
+ - Fix `deep_merge!` in Java to modify nested hashes in-place instead of duplicating them
64
+
65
+ ### Changed
66
+
67
+ - Optimize block invocation in C by using `rb_funcallv` instead of `rb_proc_call` with temporary Array allocation
68
+ - Optimize hash lookup in Java by using `fastARef` instead of `op_aref`
69
+ - Skip `to_hash` conversion when argument is already a Hash (C)
70
+ - Add `Check_Type` validation after `to_hash` conversion to ensure type safety (C)
71
+ - Use previously unused `id_call` variable for block invocation via `rb_funcallv` (C)
72
+ - Add TruffleRuby compatibility (Gemfile, C)
73
+ - Pin gem versions in Gemfile
74
+ - Refactor benchmark scripts into a single unified runner
75
+ - Add `.clang-format` configuration
76
+ - Add C and Java lint to CI (`clang-format`, `google-java-format`)
77
+ - Update `actions/checkout` v4 to v6 in CI
78
+ - Update .gitignore
79
+ - Update README.md benchmark results
80
+
81
+ ## [1.0.0] - 2025-08-11
82
+
83
+ ### Changed
84
+
85
+ - Improve performance
86
+
87
+ ### Fixed
88
+
89
+ - Update tests
90
+ - Update .gitignore
91
+ - Improve lint CI
92
+ - Update README.md
93
+
94
+ ## [0.0.2] - 2025-03-18
95
+
96
+ ### Changed
97
+
98
+ - Update summary
99
+
100
+ ## [0.0.1] - 2025-03-12
101
+
102
+ ### Fixed
103
+
104
+ - Fix permission
105
+
106
+ ### Changed
107
+
108
+ - Update tests
109
+ - Update summary
110
+ - Update README.md
111
+
112
+ ## [0.0.0] - 2025-03-11
113
+
114
+ ### Added
115
+
116
+ - Initial release
117
+
118
+ [2.0.0]: https://github.com/cadenza-tech/sin_deep_merge/compare/v1.0.2...v2.0.0
119
+ [1.0.2]: https://github.com/cadenza-tech/sin_deep_merge/compare/v1.0.1...v1.0.2
120
+ [1.0.1]: https://github.com/cadenza-tech/sin_deep_merge/compare/v1.0.0...v1.0.1
121
+ [1.0.0]: https://github.com/cadenza-tech/sin_deep_merge/compare/v0.0.2...v1.0.0
122
+ [0.0.2]: https://github.com/cadenza-tech/sin_deep_merge/compare/v0.0.1...v0.0.2
123
+ [0.0.1]: https://github.com/cadenza-tech/sin_deep_merge/compare/v0.0.0...v0.0.1
124
+ [0.0.0]: https://github.com/cadenza-tech/sin_deep_merge/releases/tag/v0.0.0
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Masahiro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,191 @@
1
+ # SinDeepMerge
2
+
3
+ [![License](https://img.shields.io/github/license/cadenza-tech/sin_deep_merge?label=License&labelColor=343B42&color=blue)](https://github.com/cadenza-tech/sin_deep_merge/blob/main/LICENSE.txt) [![Tag](https://img.shields.io/github/tag/cadenza-tech/sin_deep_merge?label=Tag&logo=github&labelColor=343B42&color=2EBC4F)](https://github.com/cadenza-tech/sin_deep_merge/blob/main/CHANGELOG.md) [![Release](https://github.com/cadenza-tech/sin_deep_merge/actions/workflows/release.yml/badge.svg)](https://github.com/cadenza-tech/sin_deep_merge/actions?query=workflow%3Arelease) [![Test](https://github.com/cadenza-tech/sin_deep_merge/actions/workflows/test.yml/badge.svg)](https://github.com/cadenza-tech/sin_deep_merge/actions?query=workflow%3Atest) [![Lint](https://github.com/cadenza-tech/sin_deep_merge/actions/workflows/lint.yml/badge.svg)](https://github.com/cadenza-tech/sin_deep_merge/actions?query=workflow%3Alint)
4
+
5
+ Merge deeply nested hashes faster than DeepMerge or ActiveSupport.
6
+
7
+ - [Installation](#installation)
8
+ - [Usage](#usage)
9
+ - [Hash#deep\_merge](#hashdeep_merge)
10
+ - [Hash#deep\_merge!](#hashdeep_merge-1)
11
+ - [Benchmark](#benchmark)
12
+ - [Changelog](#changelog)
13
+ - [Development](#development)
14
+ - [Building for JRuby](#building-for-jruby)
15
+ - [Contributing](#contributing)
16
+ - [License](#license)
17
+ - [Code of Conduct](#code-of-conduct)
18
+ - [Sponsor](#sponsor)
19
+
20
+ ## Installation
21
+
22
+ Install the gem and add to the application's Gemfile by executing:
23
+
24
+ ```bash
25
+ bundle add sin_deep_merge
26
+ ```
27
+
28
+ If bundler is not being used to manage dependencies, install the gem by executing:
29
+
30
+ ```bash
31
+ gem install sin_deep_merge
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ Both methods can be called inside non-main Ractors on CRuby 3.0+.
37
+
38
+ Requiring ActiveSupport afterwards is safe from 7.1 on, where Hash reaches both methods through `ActiveSupport::DeepMergeable` and a method defined on Hash itself wins over an included module. Up to 7.0 ActiveSupport defines them on Hash directly and replaces these when `active_support/core_ext/hash/deep_merge` is loaded last, so require `sin_deep_merge` after ActiveSupport there. `Hash.instance_method(:deep_merge).source_location` is `nil` while the extension is the one in place.
39
+
40
+ ### Hash#deep_merge
41
+
42
+ SinDeepMerge's Hash#deep_merge is compatible with ActiveSupport's Hash#deep_merge.
43
+
44
+ Hash subclasses that override `merge!` or `update`, such as `ActiveSupport::HashWithIndifferentAccess`, are merged through that override, so they behave the same as with ActiveSupport. Such a merge runs in Ruby rather than in the extension, so it is no faster than ActiveSupport.
45
+
46
+ What SinDeepMerge recurses into is any pair of Hashes, where ActiveSupport asks its `deep_merge?` hook instead. Two cases follow from that: a value that includes `ActiveSupport::DeepMergeable` without being a Hash is replaced rather than merged into, and a Hash subclass that overrides `deep_merge?` to refuse a value is merged into all the same.
47
+
48
+ ```ruby
49
+ require 'sin_deep_merge'
50
+
51
+ hash1 = { a: 1, b: '2', c: :three, d: true, e: nil }
52
+ hash2 = { b: :two, c: nil, d: false, e: 0, f: 'f' }
53
+ hash1.deep_merge(hash2) # => { a: 1, b: :two, c: nil, d: false, e: 0, f: 'f' }
54
+
55
+ hash1 = { a: [1, 2], b: [3, 4] }
56
+ hash2 = { a: [3, 4], b: 5 }
57
+ hash1.deep_merge(hash2) # => { a: [3, 4], b: 5 }
58
+
59
+ hash1 = { a: { b: 1, c: 2 }, b: { c: 3 } }
60
+ hash2 = { a: { c: 3, d: 4 }, b: 5 }
61
+ hash1.deep_merge(hash2) # => { a: { b: 1, c: 3, d: 4 }, b: 5 }
62
+
63
+ hash1 = { a: 1, b: 2 }
64
+ hash2 = { b: 3, c: 4 }
65
+ hash1.deep_merge(hash2) { |_key, old_val, new_val| old_val + new_val } # => { a: 1, b: 5, c: 4 }
66
+
67
+ hash1 = { a: [1, 2], b: 3 }
68
+ hash2 = { a: [3, 4], b: 5 }
69
+ hash1.deep_merge(hash2) do |_key, old_val, new_val|
70
+ if old_val.is_a?(Array) && new_val.is_a?(Array)
71
+ old_val + new_val
72
+ else
73
+ new_val
74
+ end
75
+ end # => { a: [1, 2, 3, 4], b: 5 }
76
+ ```
77
+
78
+ ### Hash#deep_merge!
79
+
80
+ SinDeepMerge's Hash#deep_merge! is compatible with ActiveSupport's Hash#deep_merge!.
81
+
82
+ Hash#deep_merge! destructively updates self by merging new values into it. Like ActiveSupport, nested hashes are merged into copies, so a nested hash shared with another object or a frozen nested hash is never mutated in place.
83
+
84
+ One case differs: a plain Hash carrying a singleton `merge!` is written into by the extension, so that override never runs, where ActiveSupport reaches it. Hash#deep_merge is not affected, since ActiveSupport merges into a `dup` there, and a `dup` no longer carries the singleton method.
85
+
86
+ ## Benchmark
87
+
88
+ SinDeepMerge's Hash#deep_merge is about 2.5-2.7x faster than ActiveSupport's Hash#deep_merge, and SinDeepMerge's Hash#deep_merge! is about 4.4x faster than DeepMerge's Hash#deep_merge! and about 2.4x faster than ActiveSupport's Hash#deep_merge!.
89
+
90
+ The first four tables hold only methods that leave the hash they were called on alone, so every iteration of the timed loop repeats the work of the first. DeepMerge is absent from them because it has no such method: its Hash#deep_merge writes into the receiver and returns it, the same as its Hash#deep_merge!. It also reads its second argument as an options Hash rather than as a block, so it has no block form either.
91
+
92
+ The last table is the one DeepMerge belongs in. Its entry there is Hash#deep_merge! rather than Hash#deep_merge, because Hash#deep_merge leaves an existing value alone where the other two overwrite it, and on these inputs it would walk the hash without writing anything. Every row there merges into a receiver that already carries the merge from the second iteration on. These inputs keep their shape once merged, so that costs little, but an input that grew the receiver would flatter each library by a different amount. Read those ratios as the rough comparison they are rather than as the measurement the first four tables give.
93
+
94
+ ```bash
95
+ $ bundle exec rake benchmark
96
+ Benchmarking: Shallow Recursion...
97
+ Benchmarking: Shallow Recursion With Block...
98
+ Benchmarking: Deep Recursion...
99
+ Benchmarking: Deep Recursion With Block...
100
+ Benchmarking: Deep Recursion In Place...
101
+
102
+ +--------------------------------------------------------------------------+
103
+ | Benchmark Result (Shallow Recursion) |
104
+ +----------------------------+----------------------+--------+-------------+
105
+ | Name | Iteration Per Second | Error | Speed Ratio |
106
+ +----------------------------+----------------------+--------+-------------+
107
+ | SinDeepMerge - deep_merge | 2678917.7 | ±0.56% | Fastest |
108
+ | Scratch - deep_merge | 1251682.2 | ±0.55% | 2.1x slower |
109
+ | ActiveSupport - deep_merge | 1006374.4 | ±0.53% | 2.7x slower |
110
+ +----------------------------+----------------------+--------+-------------+
111
+
112
+ +---------------------------------------------------------------------------------------------------------+
113
+ | Benchmark Result (Shallow Recursion With Block) |
114
+ +-----------------------------------------------------------+----------------------+--------+-------------+
115
+ | Name | Iteration Per Second | Error | Speed Ratio |
116
+ +-----------------------------------------------------------+----------------------+--------+-------------+
117
+ | SinDeepMerge - deep_merge (Shallow Recursion With Block) | 2283373.8 | ±0.62% | Fastest |
118
+ | Scratch - deep_merge (Shallow Recursion With Block) | 1100891.3 | ±0.50% | 2.1x slower |
119
+ | ActiveSupport - deep_merge (Shallow Recursion With Block) | 913719.8 | ±0.68% | 2.5x slower |
120
+ +-----------------------------------------------------------+----------------------+--------+-------------+
121
+
122
+ +--------------------------------------------------------------------------+
123
+ | Benchmark Result (Deep Recursion) |
124
+ +----------------------------+----------------------+--------+-------------+
125
+ | Name | Iteration Per Second | Error | Speed Ratio |
126
+ +----------------------------+----------------------+--------+-------------+
127
+ | SinDeepMerge - deep_merge | 28403.8 | ±0.78% | Fastest |
128
+ | Scratch - deep_merge | 12948.1 | ±0.76% | 2.2x slower |
129
+ | ActiveSupport - deep_merge | 11271.6 | ±0.45% | 2.5x slower |
130
+ +----------------------------+----------------------+--------+-------------+
131
+
132
+ +------------------------------------------------------------------------------------------------------+
133
+ | Benchmark Result (Deep Recursion With Block) |
134
+ +--------------------------------------------------------+----------------------+--------+-------------+
135
+ | Name | Iteration Per Second | Error | Speed Ratio |
136
+ +--------------------------------------------------------+----------------------+--------+-------------+
137
+ | SinDeepMerge - deep_merge (Deep Recursion With Block) | 27810.9 | ±0.58% | Fastest |
138
+ | Scratch - deep_merge (Deep Recursion With Block) | 12943.0 | ±0.47% | 2.1x slower |
139
+ | ActiveSupport - deep_merge (Deep Recursion With Block) | 10803.1 | ±0.56% | 2.6x slower |
140
+ +--------------------------------------------------------+----------------------+--------+-------------+
141
+
142
+ +---------------------------------------------------------------------------+
143
+ | Benchmark Result (Deep Recursion In Place) |
144
+ +-----------------------------+----------------------+--------+-------------+
145
+ | Name | Iteration Per Second | Error | Speed Ratio |
146
+ +-----------------------------+----------------------+--------+-------------+
147
+ | SinDeepMerge - deep_merge! | 27075.8 | ±0.66% | Fastest |
148
+ | ActiveSupport - deep_merge! | 11284.2 | ±0.44% | 2.4x slower |
149
+ | DeepMerge - deep_merge! | 6089.0 | ±0.62% | 4.4x slower |
150
+ +-----------------------------+----------------------+--------+-------------+
151
+ ```
152
+
153
+ Each row's error is how much its own measurement moved within that run, which is not how far that run sits from the next one. A run taken while the machine was busy reported errors just as narrow as these and ratios well away from these, so the numbers above are from a quiet machine and from two runs that agreed to within 0.1.
154
+
155
+ The error is also what decides the Speed Ratio column: a row is labelled Fastest when its gap to the top row is narrower than the two errors together, because a gap that small is the measurement failing to separate them rather than a difference it found. More than one row can therefore read Fastest.
156
+
157
+ The benchmark was executed in the following environment:
158
+
159
+ - Ruby 4.0.6 (2026-07-14 revision 03b6d3f889) +YJIT +PRISM [arm64-darwin25]
160
+ - DeepMerge 1.2.2
161
+ - ActiveSupport 8.1.3.1
162
+
163
+ ## Changelog
164
+
165
+ See [CHANGELOG.md](https://github.com/cadenza-tech/sin_deep_merge/blob/main/CHANGELOG.md).
166
+
167
+ ## Development
168
+
169
+ ### Building for JRuby
170
+
171
+ To build the Java extension and run tests for JRuby support:
172
+
173
+ ```bash
174
+ ./script/jruby_build_and_test.sh
175
+ ```
176
+
177
+ ## Contributing
178
+
179
+ Bug reports and pull requests are welcome on GitHub at https://github.com/cadenza-tech/sin_deep_merge. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/cadenza-tech/sin_deep_merge/blob/main/CODE_OF_CONDUCT.md).
180
+
181
+ ## License
182
+
183
+ The gem is available as open source under the terms of the [MIT License](https://github.com/cadenza-tech/sin_deep_merge/blob/main/LICENSE.txt).
184
+
185
+ ## Code of Conduct
186
+
187
+ Everyone interacting in the SinDeepMerge project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/cadenza-tech/sin_deep_merge/blob/main/CODE_OF_CONDUCT.md).
188
+
189
+ ## Sponsor
190
+
191
+ You can sponsor this project on [GitHub Sponsors](https://github.com/sponsors/cadenza-tech).
data/Rakefile ADDED
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+ require 'rubocop/rake_task'
6
+ require 'rubygems/package_task'
7
+
8
+ gemspec = Gem::Specification.load("#{__dir__}/sin_deep_merge.gemspec")
9
+
10
+ if RUBY_ENGINE == 'jruby'
11
+ require 'rake/javaextensiontask'
12
+
13
+ Rake::JavaExtensionTask.new('sin_deep_merge', gemspec) do |task|
14
+ task.ext_dir = 'ext/java'
15
+ task.source_version = '1.8'
16
+ task.target_version = '1.8'
17
+ end
18
+ else
19
+ require 'rake/extensiontask'
20
+
21
+ Rake::ExtensionTask.new('sin_deep_merge', gemspec) do |task|
22
+ task.lib_dir = 'lib/sin_deep_merge'
23
+ end
24
+ end
25
+
26
+ Gem::PackageTask.new(gemspec)
27
+
28
+ Rake::TestTask.new(:test) do |task|
29
+ task.pattern = 'test/**/test_*.rb'
30
+ end
31
+
32
+ # Without this the suite happily runs against a stale binary, so a changed extension looks like it passed.
33
+ Rake::Task[:test].enhance([:compile])
34
+
35
+ RuboCop::RakeTask.new(:rubocop) do |task|
36
+ task.options = ['--format', ENV['RUBOCOP_FORMAT']] if ENV['RUBOCOP_FORMAT']
37
+ end
38
+
39
+ task benchmark: [:compile] do
40
+ RubyVM::YJIT.enable if defined?(RubyVM::YJIT) && !RubyVM::YJIT.enabled?
41
+
42
+ require_relative 'script/deep_merge_benchmark'
43
+
44
+ DeepMergeBenchmark.run
45
+ end
@@ -2,4 +2,12 @@
2
2
 
3
3
  require 'mkmf'
4
4
 
5
- create_makefile 'sin_deep_merge'
5
+ # rb_ext_ractor_safe() arrived in Ruby 3.0 and the gem still supports 2.3, so Init_sin_deep_merge guards its call on this.
6
+ have_func('rb_ext_ractor_safe')
7
+ # TruffleRuby has no ruby_stack_check(), so deep_merge_hashes guards its stack check on this.
8
+ have_func('ruby_stack_check')
9
+ have_var('rb_eSysStackError', 'ruby.h')
10
+ # rb_hash_dup() skips the initialize_dup dispatch rb_obj_dup() pays for, and deep_merge_hash_dup falls back to the latter without it.
11
+ have_func('rb_hash_dup')
12
+
13
+ create_makefile 'sin_deep_merge/sin_deep_merge'
@@ -1,91 +1,119 @@
1
1
  #include <ruby.h>
2
2
 
3
- static ID id_call;
4
- static ID id_to_hash;
3
+ #if defined(HAVE_RUBY_STACK_CHECK) && defined(HAVE_RB_ESYSSTACKERROR)
4
+ #define DEEP_MERGE_STACK_GUARD
5
+ #endif
5
6
 
6
7
  typedef struct {
7
8
  VALUE hash;
8
- VALUE block;
9
- int destructive;
10
9
  int block_given;
11
10
  } deep_merge_context;
12
11
 
13
- static VALUE deep_merge_hashes(VALUE self, VALUE other, VALUE block, int destructive);
12
+ /*
13
+ * Only plain hashes are ever copied here, a subclass being handed to SinDeepMerge::Fallback instead, and a plain hash has no
14
+ * initialize_copy of its own to run. That leaves rb_obj_dup() dispatching initialize_dup for nothing, which rb_hash_dup() skips.
15
+ *
16
+ * Before Ruby 3.3 that shortcut loses compare_by_identity from a hash holding nothing, since the flag lives on a table an empty hash has
17
+ * yet to allocate. Copying an empty hash costs the same either way, so it goes the general route and the shortcut is left to the rest.
18
+ */
19
+ static VALUE deep_merge_hash_dup(VALUE hash) {
20
+ #ifdef HAVE_RB_HASH_DUP
21
+ if (RHASH_SIZE(hash) > 0) return rb_hash_dup(hash);
22
+ #endif
23
+
24
+ return rb_obj_dup(hash);
25
+ }
26
+
27
+ static VALUE deep_merge_hashes(VALUE self, VALUE other, int block_given);
28
+
29
+ /*
30
+ * A Hash subclass may override merge! or update to police what gets stored, as ActiveSupport's HashWithIndifferentAccess does to keep its
31
+ * keys strings. rb_hash_aset writes past that override, so those receivers go to SinDeepMerge::Fallback, which is ActiveSupport's own
32
+ * implementation and therefore reaches the override through merge!. rb_obj_class sees through a singleton class, so a plain hash carrying
33
+ * singleton methods still takes the fast path.
34
+ */
35
+ static int plain_hash_p(VALUE hash) { return rb_obj_class(hash) == rb_cHash; }
36
+
37
+ static VALUE deep_merge_forward(VALUE recv, ID mid, int argc, const VALUE* argv) {
38
+ if (!rb_block_given_p()) return rb_funcallv(recv, mid, argc, argv);
39
+
40
+ /* rb_funcall_passing_block would spare the Proc, but Sulong lacks it up to TruffleRuby 22.3. */
41
+ return rb_funcall_with_block(recv, mid, argc, argv, rb_block_proc());
42
+ }
43
+
44
+ static VALUE deep_merge_fallback(VALUE self, VALUE other, const char* name) {
45
+ VALUE args[2] = {self, other};
46
+
47
+ return deep_merge_forward(rb_path2class("SinDeepMerge::Fallback"), rb_intern(name), 2, args);
48
+ }
14
49
 
15
50
  static int deep_merge_iter(VALUE key, VALUE other_val, VALUE data) {
16
51
  deep_merge_context* ctx = (deep_merge_context*)data;
17
52
  VALUE current_val = rb_hash_lookup2(ctx->hash, key, Qundef);
18
-
19
- if (current_val == Qundef) {
20
- rb_hash_aset(ctx->hash, key, other_val);
21
- } else if (RB_TYPE_P(current_val, T_HASH) && RB_TYPE_P(other_val, T_HASH)) {
22
- VALUE merged;
23
- if (ctx->destructive) {
24
- merged = deep_merge_hashes(current_val, other_val, ctx->block, 1);
25
- } else {
26
- merged = deep_merge_hashes(rb_obj_dup(current_val), other_val, ctx->block, 0);
53
+ VALUE new_val = other_val;
54
+
55
+ /* An absent key takes other_val as is, which is what new_val already holds. */
56
+ if (current_val != Qundef) {
57
+ if (RB_TYPE_P(current_val, T_HASH) && RB_TYPE_P(other_val, T_HASH)) {
58
+ /* Merge into a copy like ActiveSupport so shared or frozen nested hashes are never mutated. */
59
+ new_val = plain_hash_p(current_val)
60
+ ? deep_merge_hashes(deep_merge_hash_dup(current_val), other_val, ctx->block_given)
61
+ /* ActiveSupport recurses as this_val.deep_merge(other_val), so a nested subclass gets its own override too. */
62
+ : deep_merge_forward(current_val, rb_intern("deep_merge"), 1, &other_val);
63
+ } else if (ctx->block_given) {
64
+ /* Yield directly: no Proc to allocate, and it avoids rb_proc_call_with_block, which Sulong lacks up to TruffleRuby 23.0. */
65
+ new_val = rb_yield_values(3, key, current_val, other_val);
27
66
  }
28
- rb_hash_aset(ctx->hash, key, merged);
29
- } else if (ctx->block_given) {
30
- VALUE args[3] = {key, current_val, other_val};
31
- /* rb_funcallv for TruffleRuby compat (Sulong lacks rb_proc_call_with_block) */
32
- VALUE result = rb_funcallv(ctx->block, id_call, 3, args);
33
- rb_hash_aset(ctx->hash, key, result);
34
- } else {
35
- rb_hash_aset(ctx->hash, key, other_val);
36
67
  }
37
68
 
69
+ rb_hash_aset(ctx->hash, key, new_val);
70
+
38
71
  return ST_CONTINUE;
39
72
  }
40
73
 
41
- static VALUE deep_merge_hashes(VALUE self, VALUE other, VALUE block, int destructive) {
42
- int block_given = !NIL_P(block);
43
- deep_merge_context ctx = {self, block, destructive, block_given};
74
+ static VALUE deep_merge_hashes(VALUE self, VALUE other, int block_given) {
75
+ deep_merge_context ctx = {self, block_given};
76
+
77
+ #ifdef DEEP_MERGE_STACK_GUARD
78
+ /* Raise while stack remains; overflowing the machine stack guard from C recursion can crash the process on a later overflow. */
79
+ if (ruby_stack_check()) rb_raise(rb_eSysStackError, "stack level too deep");
80
+ #endif
44
81
 
45
82
  rb_hash_foreach(other, deep_merge_iter, (VALUE)&ctx);
46
83
 
47
84
  return self;
48
85
  }
49
86
 
50
- static VALUE hash_deep_merge_bang(int argc, VALUE* argv, VALUE self) {
51
- VALUE other;
52
- rb_scan_args(argc, argv, "1", &other);
53
- rb_check_frozen(self);
54
- if (!RB_TYPE_P(other, T_HASH)) {
55
- other = rb_funcall(other, id_to_hash, 0);
56
- Check_Type(other, T_HASH);
57
- }
58
- VALUE block = Qnil;
59
- if (rb_block_given_p()) {
60
- block = rb_block_proc();
61
- }
87
+ static VALUE hash_deep_merge_bang(VALUE self, VALUE other) {
88
+ /* Hand over before converting other: a subclass may treat a Hash and a to_hash convertible differently, as merge! is free to. */
89
+ if (!plain_hash_p(self)) return deep_merge_fallback(self, other, "deep_merge!");
62
90
 
63
- deep_merge_hashes(self, other, block, 1);
91
+ rb_check_frozen(self);
92
+ other = rb_convert_type(other, T_HASH, "Hash", "to_hash");
64
93
 
65
- return self;
94
+ return deep_merge_hashes(self, other, rb_block_given_p());
66
95
  }
67
96
 
68
- static VALUE hash_deep_merge(int argc, VALUE* argv, VALUE self) {
69
- VALUE other;
70
- rb_scan_args(argc, argv, "1", &other);
71
- if (!RB_TYPE_P(other, T_HASH)) {
72
- other = rb_funcall(other, id_to_hash, 0);
73
- Check_Type(other, T_HASH);
74
- }
75
- VALUE block = Qnil;
76
- if (rb_block_given_p()) {
77
- block = rb_block_proc();
78
- }
97
+ static VALUE hash_deep_merge(VALUE self, VALUE other) {
98
+ if (!plain_hash_p(self)) return deep_merge_fallback(self, other, "deep_merge");
79
99
 
80
- VALUE duplicated = rb_obj_dup(self);
81
- deep_merge_hashes(duplicated, other, block, 0);
100
+ other = rb_convert_type(other, T_HASH, "Hash", "to_hash");
82
101
 
83
- return duplicated;
102
+ return deep_merge_hashes(deep_merge_hash_dup(self), other, rb_block_given_p());
84
103
  }
85
104
 
86
105
  void Init_sin_deep_merge(void) {
87
- id_call = rb_intern("call");
88
- id_to_hash = rb_intern("to_hash");
89
- rb_define_method(rb_cHash, "deep_merge", RUBY_METHOD_FUNC(hash_deep_merge), -1);
90
- rb_define_method(rb_cHash, "deep_merge!", RUBY_METHOD_FUNC(hash_deep_merge_bang), -1);
106
+ /*
107
+ * Declaring this is a promise, and what backs it is that there is no file-scope state at all, and that every write lands on a hash the
108
+ * calling Ractor owns: deep_merge builds a dup and writes into that, and deep_merge! is kept off a shareable receiver, which is frozen by
109
+ * definition, either by rb_check_frozen or by the frozen check merge! runs on the subclass path. The only thing reached for outside the
110
+ * arguments is the SinDeepMerge::Fallback constant, and a module is shareable. It has to run before the definitions, because what it marks
111
+ * is whatever is defined after it.
112
+ */
113
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
114
+ rb_ext_ractor_safe(true);
115
+ #endif
116
+
117
+ rb_define_method(rb_cHash, "deep_merge", RUBY_METHOD_FUNC(hash_deep_merge), 1);
118
+ rb_define_method(rb_cHash, "deep_merge!", RUBY_METHOD_FUNC(hash_deep_merge_bang), 1);
91
119
  }
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SinDeepMerge
4
+ # ActiveSupport's implementation, kept for Hash subclasses that override merge! or update, ActiveSupport's
5
+ # HashWithIndifferentAccess being the common one. The extensions write straight into the storage of the hash, which skips such an
6
+ # override, so they hand those receivers here instead. dup and merge! are called on the receiver so that its own overrides run.
7
+ module Fallback # :nodoc:
8
+ module_function
9
+
10
+ def deep_merge(hash, other_hash, &block)
11
+ deep_merge!(hash.dup, other_hash, &block)
12
+ end
13
+
14
+ def deep_merge!(hash, other_hash, &block)
15
+ hash.merge!(other_hash) do |key, this_val, other_val|
16
+ if this_val.is_a?(Hash) && other_val.is_a?(Hash)
17
+ this_val.deep_merge(other_val, &block)
18
+ elsif block
19
+ yield(key, this_val, other_val)
20
+ else
21
+ other_val
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SinDeepMerge
4
+ VERSION = '2.0.0'
5
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Hash
4
+ # Explicitly undefine method before redefining to avoid Ruby warnings.
5
+ undef_method(:deep_merge) if method_defined?(:deep_merge)
6
+ undef_method(:deep_merge!) if method_defined?(:deep_merge!)
7
+ end
8
+
9
+ # Both extensions look this up by name when they meet a Hash subclass, so it has to be in place before they can be called.
10
+ require 'sin_deep_merge/fallback'
11
+
12
+ case RUBY_ENGINE
13
+ when 'jruby'
14
+ require 'jruby'
15
+ require 'sin_deep_merge/sin_deep_merge.jar'
16
+
17
+ Java::sin_deep_merge::SinDeepMergeLibrary.new.load(JRuby.runtime, false)
18
+ else
19
+ # The extension-less require lets Ruby resolve the platform-specific shared library suffix (.bundle on macOS, .so elsewhere) via DLEXT.
20
+ require 'sin_deep_merge/sin_deep_merge'
21
+ end
22
+
23
+ require 'sin_deep_merge/version'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sin_deep_merge
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.2
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Masahiro
@@ -17,18 +17,25 @@ extensions:
17
17
  - ext/sin_deep_merge/extconf.rb
18
18
  extra_rdoc_files: []
19
19
  files:
20
+ - CHANGELOG.md
21
+ - LICENSE.txt
22
+ - README.md
23
+ - Rakefile
20
24
  - ext/sin_deep_merge/extconf.rb
21
25
  - ext/sin_deep_merge/sin_deep_merge.c
22
- homepage: https://github.com/cadenza-tech/sin_deep_merge/tree/v1.0.2
26
+ - lib/sin_deep_merge.rb
27
+ - lib/sin_deep_merge/fallback.rb
28
+ - lib/sin_deep_merge/version.rb
29
+ homepage: https://github.com/cadenza-tech/sin_deep_merge/tree/v2.0.0
23
30
  licenses:
24
31
  - MIT
25
32
  metadata:
26
- homepage_uri: https://github.com/cadenza-tech/sin_deep_merge/tree/v1.0.2
27
- source_code_uri: https://github.com/cadenza-tech/sin_deep_merge/tree/v1.0.2
28
- changelog_uri: https://github.com/cadenza-tech/sin_deep_merge/blob/v1.0.2/CHANGELOG.md
33
+ homepage_uri: https://github.com/cadenza-tech/sin_deep_merge/tree/v2.0.0
34
+ source_code_uri: https://github.com/cadenza-tech/sin_deep_merge/tree/v2.0.0
35
+ changelog_uri: https://github.com/cadenza-tech/sin_deep_merge/blob/v2.0.0/CHANGELOG.md
29
36
  bug_tracker_uri: https://github.com/cadenza-tech/sin_deep_merge/issues
30
- documentation_uri: https://rubydoc.info/gems/sin_deep_merge/1.0.2
31
- funding_uri: https://patreon.com/CadenzaTech
37
+ documentation_uri: https://rubydoc.info/gems/sin_deep_merge/2.0.0
38
+ funding_uri: https://github.com/sponsors/cadenza-tech
32
39
  rubygems_mfa_required: 'true'
33
40
  rdoc_options: []
34
41
  require_paths:
@@ -44,7 +51,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
44
51
  - !ruby/object:Gem::Version
45
52
  version: '0'
46
53
  requirements: []
47
- rubygems_version: 3.6.9
54
+ rubygems_version: 4.0.16
48
55
  specification_version: 4
49
56
  summary: Merge deeply nested hashes faster than DeepMerge or ActiveSupport
50
57
  test_files: []