From 0c737ae8d2ec5d6b496fd29a4e607fd7f8b15772 Mon Sep 17 00:00:00 2001 From: Aviv Palivoda Date: Fri, 8 Feb 2019 17:31:45 +0200 Subject: [PATCH] Add set.__eq__ --- tests/snippets/set.py | 3 +++ vm/src/obj/objset.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/tests/snippets/set.py b/tests/snippets/set.py index eda3e7702..22f1262b5 100644 --- a/tests/snippets/set.py +++ b/tests/snippets/set.py @@ -1,2 +1,5 @@ +assert set([1,2]) == set([1,2]) +assert not set([1,2,3]) == set([1,2]) + assert set([1,2,3]) >= set([1,2]) assert not set([1,3]) >= set([1,2]) diff --git a/vm/src/obj/objset.rs b/vm/src/obj/objset.rs index 85a01e294..8c7b66266 100644 --- a/vm/src/obj/objset.rs +++ b/vm/src/obj/objset.rs @@ -148,6 +148,33 @@ fn set_ge(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(vm.new_bool(true)) } +fn set_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!( + vm, + args, + required = [ + (zelf, Some(vm.ctx.set_type())), + (other, Some(vm.ctx.set_type())) + ] + ); + let zelf_elements = get_elements(zelf); + let other_elements = get_elements(other); + if zelf_elements.len() != other_elements.len() { + return Ok(vm.new_bool(false)); + } + for element in zelf_elements.iter() { + match vm.call_method(other, "__contains__", vec![element.1.clone()]) { + Ok(value) => { + if !objbool::get_value(&value) { + return Ok(vm.new_bool(false)); + } + } + Err(_) => return Err(vm.new_type_error("".to_string())), + } + } + Ok(vm.new_bool(true)) +} + fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]); @@ -181,6 +208,7 @@ pub fn init(context: &PyContext) { context.set_attr(&set_type, "__len__", context.new_rustfunc(set_len)); context.set_attr(&set_type, "__new__", context.new_rustfunc(set_new)); context.set_attr(&set_type, "__repr__", context.new_rustfunc(set_repr)); + context.set_attr(&set_type, "__eq__", context.new_rustfunc(set_eq)); context.set_attr(&set_type, "__ge__", context.new_rustfunc(set_ge)); context.set_attr(&set_type, "__doc__", context.new_str(set_doc.to_string())); context.set_attr(&set_type, "add", context.new_rustfunc(set_add));