Add bytes.__iter__

This commit is contained in:
Homer McMillan
2019-02-05 21:44:14 -05:00
parent aaf0eab530
commit 35a06bc428
2 changed files with 29 additions and 0 deletions

View File

@@ -20,6 +20,7 @@ pub fn init(context: &PyContext) {
context.set_attr(bytes_type, "__new__", context.new_rustfunc(bytes_new));
context.set_attr(bytes_type, "__repr__", context.new_rustfunc(bytes_repr));
context.set_attr(bytes_type, "__len__", context.new_rustfunc(bytes_len));
context.set_attr(bytes_type, "__iter__", context.new_rustfunc(bytes_iter))
}
fn bytes_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
@@ -101,3 +102,17 @@ fn bytes_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
let data = String::from_utf8(value.to_vec()).unwrap();
Ok(vm.new_str(format!("b'{}'", data)))
}
fn bytes_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytes_type()))]);
let iter_obj = PyObject::new(
PyObjectPayload::Iterator {
position: 0,
iterated_obj: obj.clone(),
},
vm.ctx.iter_type(),
);
Ok(iter_obj)
}

View File

@@ -131,6 +131,20 @@ fn iter_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
Err(stop_iteration)
}
}
PyObjectPayload::Bytes { ref value } => {
if *position < value.len() {
let obj_ref = vm.ctx.new_int(value[*position].to_bigint().unwrap());
*position += 1;
Ok(obj_ref)
} else {
let stop_iteration_type = vm.ctx.exceptions.stop_iteration.clone();
let stop_iteration =
vm.new_exception(stop_iteration_type, "End of iterator".to_string());
Err(stop_iteration)
}
}
_ => {
panic!("NOT IMPL");
}