Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some Hash destructive methods ensure the receiver modifiable [Bug #17736] #4297

Merged
merged 1 commit into from
Mar 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -2476,6 +2476,7 @@ static int
delete_if_i(VALUE key, VALUE value, VALUE hash)
{
if (RTEST(rb_yield_values(2, key, value))) {
rb_hash_modify(hash);
return ST_DELETE;
}
return ST_CONTINUE;
Expand Down Expand Up @@ -2705,6 +2706,7 @@ static int
keep_if_i(VALUE key, VALUE value, VALUE hash)
{
if (!RTEST(rb_yield_values(2, key, value))) {
rb_hash_modify(hash);
return ST_DELETE;
}
return ST_CONTINUE;
Expand Down
42 changes: 42 additions & 0 deletions test/ruby/test_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -439,13 +439,30 @@ def test_delete_if
true
}
assert_equal(base.size, n)

h = base.dup
assert_raise(FrozenError) do
h.delete_if do
h.freeze
true
end
end
assert_equal(base.dup, h)
end

def test_keep_if
h = @cls[1=>2,3=>4,5=>6]
assert_equal({3=>4,5=>6}, h.keep_if {|k, v| k + v >= 7 })
h = @cls[1=>2,3=>4,5=>6]
assert_equal({1=>2,3=>4,5=>6}, h.keep_if{true})
h = @cls[1=>2,3=>4,5=>6]
assert_raise(FrozenError) do
h.keep_if do
h.freeze
false
end
end
assert_equal(@cls[1=>2,3=>4,5=>6], h)
end

def test_compact
Expand Down Expand Up @@ -743,6 +760,15 @@ def test_reject!
h = base.dup
assert_equal(h3, h.reject! {|k,v| v })
assert_equal(h3, h)

h = base.dup
assert_raise(FrozenError) do
h.reject! do
h.freeze
true
end
end
assert_equal(base.dup, h)
end

def test_replace
Expand Down Expand Up @@ -1046,6 +1072,14 @@ def test_select!
assert_equal({3=>4,5=>6}, h)
h = @cls[1=>2,3=>4,5=>6]
assert_equal(nil, h.select!{true})
h = @cls[1=>2,3=>4,5=>6]
assert_raise(FrozenError) do
h.select! do
h.freeze
false
end
end
assert_equal(@cls[1=>2,3=>4,5=>6], h)
end

def test_slice
Expand Down Expand Up @@ -1098,6 +1132,14 @@ def test_filter!
assert_equal({3=>4,5=>6}, h)
h = @cls[1=>2,3=>4,5=>6]
assert_equal(nil, h.filter!{true})
h = @cls[1=>2,3=>4,5=>6]
assert_raise(FrozenError) do
h.filter! do
h.freeze
false
end
end
assert_equal(@cls[1=>2,3=>4,5=>6], h)
end

def test_clear2
Expand Down