Skip to content

Commit a4b814e

Browse files
committed
Add set.intersection_update
1 parent 5f3664e commit a4b814e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

tests/snippets/set.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,8 @@ def __hash__(self):
9898
a.update([3,4,5])
9999
assert a == set([1,2,3,4,5])
100100
assert_raises(TypeError, lambda: a.update(1))
101+
102+
a = set([1,2,3])
103+
a.intersection_update([2,3,4,5])
104+
assert a == set([2,3])
105+
assert_raises(TypeError, lambda: a.intersection_update(1))

vm/src/obj/objset.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,29 @@ fn set_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
453453
}
454454
}
455455

456+
fn set_intersection_update(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
457+
arg_check!(
458+
vm,
459+
args,
460+
required = [(zelf, Some(vm.ctx.set_type())), (iterable, None)]
461+
);
462+
463+
let mut mut_obj = zelf.borrow_mut();
464+
465+
match mut_obj.payload {
466+
PyObjectPayload::Set { ref mut elements } => {
467+
for element in elements.clone().iter() {
468+
let value = vm.call_method(iterable, "__contains__", vec![element.1.clone()])?;
469+
if !objbool::get_value(&value) {
470+
elements.remove(&element.0.clone());
471+
}
472+
}
473+
Ok(vm.get_none())
474+
}
475+
_ => Err(vm.new_type_error("".to_string())),
476+
}
477+
}
478+
456479
fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
457480
arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]);
458481

@@ -525,6 +548,11 @@ pub fn init(context: &PyContext) {
525548
context.set_attr(&set_type, "copy", context.new_rustfunc(set_copy));
526549
context.set_attr(&set_type, "pop", context.new_rustfunc(set_pop));
527550
context.set_attr(&set_type, "update", context.new_rustfunc(set_update));
551+
context.set_attr(
552+
&set_type,
553+
"intersection_update",
554+
context.new_rustfunc(set_intersection_update),
555+
);
528556

529557
let frozenset_type = &context.frozenset_type;
530558

0 commit comments

Comments
 (0)