Fix Set#^ to not mutate its argument (#15296)

* test(set): add test Set#xor does not mutate other_set

* Fix Set#^ to not mutate its argument
This commit is contained in:
Gil Desmarais 2025-12-11 17:38:39 +01:00 committed by GitHub
parent 3831a82d19
commit b5604833a3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
Notes: git 2025-12-11 16:39:07 +00:00
Merged-By: knu <knu@idaemons.org>
2 changed files with 18 additions and 5 deletions

12
set.c
View File

@ -1291,15 +1291,17 @@ set_xor_i(st_data_t key, st_data_t data)
static VALUE
set_i_xor(VALUE set, VALUE other)
{
VALUE new_set;
VALUE new_set = rb_obj_dup(set);
if (rb_obj_is_kind_of(other, rb_cSet)) {
new_set = other;
set_iter(other, set_xor_i, (st_data_t)new_set);
}
else {
new_set = set_s_alloc(rb_obj_class(set));
set_merge_enum_into(new_set, other);
VALUE tmp = set_s_alloc(rb_cSet);
set_merge_enum_into(tmp, other);
set_iter(tmp, set_xor_i, (st_data_t)new_set);
}
set_iter(set, set_xor_i, (st_data_t)new_set);
return new_set;
}

View File

@ -703,6 +703,17 @@ class TC_Set < Test::Unit::TestCase
}
end
def test_xor_does_not_mutate_other_set
a = Set[1]
b = Set[1, 2]
original_b = b.dup
result = a ^ b
assert_equal(original_b, b)
assert_equal(Set[2], result)
end
def test_eq
set1 = Set[2,3,1]
set2 = Set[1,2,3]