Skip to content

Commit d4020dd

Browse files
viralpraxisknu
authored andcommitted
[Bug #21513] Raise on converting endless range to set
ref: https://bugs.ruby-lang.org/issues/21513 Before this patch, trying to convert endless range (e.g. `(1..)`) to set (using `to_set`) would hang
1 parent d9a14c2 commit d4020dd

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

set.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,14 @@ set_i_initialize(int argc, VALUE *argv, VALUE set)
505505
}
506506
}
507507
else {
508+
ID id_size = rb_intern("size");
509+
if (rb_obj_is_kind_of(other, rb_mEnumerable) && rb_respond_to(other, id_size)) {
510+
VALUE size = rb_funcall(other, id_size, 0);
511+
if (RB_TYPE_P(size, T_FLOAT) && RFLOAT_VALUE(size) == INFINITY) {
512+
rb_raise(rb_eArgError, "cannot initialize Set from an object with infinite size");
513+
}
514+
}
515+
508516
rb_block_call(other, enum_method_id(other), 0, 0,
509517
rb_block_given_p() ? set_initialize_with_block : set_initialize_without_block,
510518
set);

test/ruby/test_set.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,20 @@ def test_s_new
8181

8282
s = Set.new(ary) { |o| o * 2 }
8383
assert_equal([2,4,6], s.sort)
84+
85+
assert_raise(ArgumentError) {
86+
Set.new((1..))
87+
}
88+
assert_raise(ArgumentError) {
89+
Set.new((1..), &:succ)
90+
}
91+
assert_raise(ArgumentError) {
92+
Set.new(1.upto(Float::INFINITY))
93+
}
94+
95+
assert_raise(ArgumentError) {
96+
Set.new(Object.new)
97+
}
8498
end
8599

86100
def test_clone

0 commit comments

Comments
 (0)