Skip to content

Commit 85110f6

Browse files
committed
Add dict.clear and bytes.clear
1 parent fcea845 commit 85110f6

File tree

4 files changed

+33
-0
lines changed

4 files changed

+33
-0
lines changed

tests/snippets/bytearray.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,7 @@
2929

3030
assert bytearray(b'Is Title Case').istitle()
3131
assert not bytearray(b'is Not title casE').istitle()
32+
33+
a = b'abcd'
34+
a.clear()
35+
assert len(a) == 0

tests/snippets/dict.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,6 @@ def dict_eq(d1, d2):
1414
c['a']['g'] = 2
1515
assert dict_eq(a, {'g': 2})
1616
assert dict_eq(b, {'a': a, 'd': 9})
17+
18+
a.clear()
19+
assert len(a) == 0

vm/src/obj/objbytes.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ pub fn init(context: &PyContext) {
4141
"__doc__",
4242
context.new_str(bytes_doc.to_string()),
4343
);
44+
context.set_attr(bytes_type, "clear", context.new_rustfunc(bytes_clear));
4445
}
4546

4647
fn bytes_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
@@ -208,3 +209,15 @@ fn bytes_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
208209

209210
Ok(iter_obj)
210211
}
212+
213+
fn bytes_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
214+
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytes_type()))]);
215+
let mut mut_obj = zelf.borrow_mut();
216+
match mut_obj.payload {
217+
PyObjectPayload::Bytes { ref mut value } => {
218+
value.clear();
219+
Ok(vm.get_none())
220+
}
221+
_ => Err(vm.new_type_error("".to_string())),
222+
}
223+
}

vm/src/obj/objdict.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,18 @@ fn dict_delitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
244244
}
245245
}
246246

247+
fn dict_clear(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
248+
arg_check!(vm, args, required = [(dict, Some(vm.ctx.dict_type()))]);
249+
let mut mut_obj = dict.borrow_mut();
250+
match mut_obj.payload {
251+
PyObjectPayload::Dict { ref mut elements } => {
252+
elements.clear();
253+
Ok(vm.get_none())
254+
}
255+
_ => Err(vm.new_type_error("".to_string())),
256+
}
257+
}
258+
247259
/// When iterating over a dictionary, we iterate over the keys of it.
248260
fn dict_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
249261
arg_check!(vm, args, required = [(dict, Some(vm.ctx.dict_type()))]);
@@ -337,4 +349,5 @@ pub fn init(context: &PyContext) {
337349
"__setitem__",
338350
context.new_rustfunc(dict_setitem),
339351
);
352+
context.set_attr(&dict_type, "clear", context.new_rustfunc(dict_clear));
340353
}

0 commit comments

Comments
 (0)