From 85110f6fbf01ac927ca61bd44f9c01fd79195e4c Mon Sep 17 00:00:00 2001 From: janczer Date: Mon, 18 Feb 2019 18:21:39 +0100 Subject: [PATCH] Add dict.clear and bytes.clear --- tests/snippets/bytearray.py | 4 ++++ tests/snippets/dict.py | 3 +++ vm/src/obj/objbytes.rs | 13 +++++++++++++ vm/src/obj/objdict.rs | 13 +++++++++++++ 4 files changed, 33 insertions(+) diff --git a/tests/snippets/bytearray.py b/tests/snippets/bytearray.py index 2fffe3111..fdada9095 100644 --- a/tests/snippets/bytearray.py +++ b/tests/snippets/bytearray.py @@ -29,3 +29,7 @@ assert not bytearray(b'tuPpEr').isupper() assert bytearray(b'Is Title Case').istitle() assert not bytearray(b'is Not title casE').istitle() + +a = b'abcd' +a.clear() +assert len(a) == 0 diff --git a/tests/snippets/dict.py b/tests/snippets/dict.py index ca9d61aa6..1e4acc3e3 100644 --- a/tests/snippets/dict.py +++ b/tests/snippets/dict.py @@ -14,3 +14,6 @@ c['d'] = 3 c['a']['g'] = 2 assert dict_eq(a, {'g': 2}) assert dict_eq(b, {'a': a, 'd': 9}) + +a.clear() +assert len(a) == 0 diff --git a/vm/src/obj/objbytes.rs b/vm/src/obj/objbytes.rs index 6c8ab30ed..99f72ac65 100644 --- a/vm/src/obj/objbytes.rs +++ b/vm/src/obj/objbytes.rs @@ -41,6 +41,7 @@ pub fn init(context: &PyContext) { "__doc__", context.new_str(bytes_doc.to_string()), ); + context.set_attr(bytes_type, "clear", context.new_rustfunc(bytes_clear)); } fn bytes_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { @@ -208,3 +209,15 @@ fn bytes_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { Ok(iter_obj) } + +fn bytes_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytes_type()))]); + let mut mut_obj = zelf.borrow_mut(); + match mut_obj.payload { + PyObjectPayload::Bytes { ref mut value } => { + value.clear(); + Ok(vm.get_none()) + } + _ => Err(vm.new_type_error("".to_string())), + } +} diff --git a/vm/src/obj/objdict.rs b/vm/src/obj/objdict.rs index 3e4a7fadd..65fda7e47 100644 --- a/vm/src/obj/objdict.rs +++ b/vm/src/obj/objdict.rs @@ -244,6 +244,18 @@ fn dict_delitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } +fn dict_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!(vm, args, required = [(dict, Some(vm.ctx.dict_type()))]); + let mut mut_obj = dict.borrow_mut(); + match mut_obj.payload { + PyObjectPayload::Dict { ref mut elements } => { + elements.clear(); + Ok(vm.get_none()) + } + _ => Err(vm.new_type_error("".to_string())), + } +} + /// When iterating over a dictionary, we iterate over the keys of it. fn dict_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(dict, Some(vm.ctx.dict_type()))]); @@ -337,4 +349,5 @@ pub fn init(context: &PyContext) { "__setitem__", context.new_rustfunc(dict_setitem), ); + context.set_attr(&dict_type, "clear", context.new_rustfunc(dict_clear)); }