Skip to content

Commit

Permalink
Fix Concurrent::Map default_proc arguments
Browse files Browse the repository at this point in the history
* Fixes #993
  • Loading branch information
eregon committed Feb 24, 2023
1 parent 8cccba9 commit f2985bd
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## Current

## Release v1.2.2 (24 Feb 2023)

* (#993) Fix arguments passed to `Concurrent::Map`'s `default_proc`.

## Release v1.2.1 (24 Feb 2023)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class NonConcurrentMapBackend
# reasons.
def initialize(options = nil, &default_proc)
validate_options_hash!(options) if options.kind_of?(::Hash)
@backend = Hash.new(&default_proc)
set_backend(default_proc)
@default_proc = default_proc
end

Expand Down Expand Up @@ -113,9 +113,17 @@ def get_or_default(key, default_value)

private

def set_backend(default_proc)
if default_proc
@backend = ::Hash.new { |_h, key| default_proc.call(self, key) }
else
@backend = {}
end
end

def initialize_copy(other)
super
@backend = Hash.new(&@default_proc)
set_backend(@default_proc)
self
end

Expand Down
2 changes: 1 addition & 1 deletion lib/concurrent-ruby/concurrent/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Concurrent
VERSION = '1.2.1'
VERSION = '1.2.2'
end
25 changes: 25 additions & 0 deletions spec/concurrent/map_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@ module Concurrent
@cache = described_class.new
end

it 'default_proc is called with the Concurrent::Map and the key' do
map = Concurrent::Map.new do |h, k|
[h, k]
end
expect(map[:foo][0]).to be(map)
expect(map[:foo][1]).to eq(:foo)
end

it 'default_proc is called with the Concurrent::Map and the key after #dup' do
map = Concurrent::Map.new do |h, k|
[h, k]
end
copy = map.dup
expect(copy[:foo][0]).to be(copy)
expect(copy[:foo][1]).to eq(:foo)
end

it 'concurrency' do
(1..Concurrent::ThreadSafe::Test::THREADS).map do |i|
in_thread do
Expand Down Expand Up @@ -45,6 +62,14 @@ module Concurrent
end

describe '#compute_if_absent' do
it 'works in default_proc' do
map = Concurrent::Map.new do |map, key|
map.compute_if_absent(key) { key * 2 }
end
expect(map[3]).to eq 6
expect(map.keys).to eq [3]
end

it 'common' do
with_or_without_default_proc do
expect_size_change(3) do
Expand Down

0 comments on commit f2985bd

Please sign in to comment.