Skip to content

Commit fcea845

Browse files
Merge pull request RustPython#473 from janczer/add_list_copy
Add copy method to set object
2 parents 16832c8 + a47e979 commit fcea845

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

tests/snippets/set.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,5 +77,12 @@ def __hash__(self):
7777
a = set([1, 2, 3])
7878
assert a.discard(1) is None
7979
assert not 1 in a
80-
8180
assert a.discard(42) is None
81+
82+
a = set([1,2,3])
83+
b = a.copy()
84+
assert len(a) == 3
85+
assert len(b) == 3
86+
b.clear()
87+
assert len(a) == 3
88+
assert len(b) == 0

vm/src/obj/objset.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,16 @@ fn set_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
178178
Ok(vm.context().new_int(elements.len()))
179179
}
180180

181+
fn set_copy(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
182+
trace!("set.copy called with: {:?}", args);
183+
arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]);
184+
let elements = get_elements(s);
185+
Ok(PyObject::new(
186+
PyObjectPayload::Set { elements },
187+
vm.ctx.set_type(),
188+
))
189+
}
190+
181191
fn set_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
182192
arg_check!(vm, args, required = [(o, Some(vm.ctx.set_type()))]);
183193

@@ -477,6 +487,7 @@ pub fn init(context: &PyContext) {
477487
context.set_attr(&set_type, "remove", context.new_rustfunc(set_remove));
478488
context.set_attr(&set_type, "discard", context.new_rustfunc(set_discard));
479489
context.set_attr(&set_type, "clear", context.new_rustfunc(set_clear));
490+
context.set_attr(&set_type, "copy", context.new_rustfunc(set_copy));
480491

481492
let frozenset_type = &context.frozenset_type;
482493

0 commit comments

Comments
 (0)