mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
Add bytes.__iter__
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user