Skip to content

Commit cbd8d7b

Browse files
committed
len attributes on byte types
1 parent 278e1a8 commit cbd8d7b

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

vm/src/obj/objbytearray.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ pub fn init(context: &PyContext) {
2828
"__repr__",
2929
context.new_rustfunc(bytearray_repr),
3030
);
31+
context.set_attr(
32+
&bytearray_type,
33+
"__len__",
34+
context.new_rustfunc(bytearray_type),
35+
);
3136
}
3237

3338
fn bytearray_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
@@ -61,6 +66,18 @@ fn bytearray_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
6166
))
6267
}
6368

69+
fn bytesarray_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
70+
arg_check!(
71+
vm,
72+
args,
73+
required = [(a, Some(vm.ctx.bytearray_type()))]
74+
);
75+
76+
let byte_vec = get_value(a).to_vec();
77+
Ok(vm.ctx.new_int(byte_vec.len()))
78+
}
79+
80+
6481
fn bytearray_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
6582
arg_check!(
6683
vm,

vm/src/obj/objbytes.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ pub fn init(context: &PyContext) {
1818
context.set_attr(bytes_type, "__hash__", context.new_rustfunc(bytes_hash));
1919
context.set_attr(bytes_type, "__new__", context.new_rustfunc(bytes_new));
2020
context.set_attr(bytes_type, "__repr__", context.new_rustfunc(bytes_repr));
21+
context.set_attr(bytes_type, "__len__", context.new_rustfunc(bytes_len));
22+
2123
}
2224

2325
fn bytes_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
@@ -66,6 +68,18 @@ fn bytes_eq(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
6668
Ok(vm.ctx.new_bool(result))
6769
}
6870

71+
fn bytes_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
72+
arg_check!(
73+
vm,
74+
args,
75+
required = [(a, Some(vm.ctx.bytes_type()))]
76+
);
77+
78+
let byte_vec = get_value(a).to_vec();
79+
Ok(vm.ctx.new_int(byte_vec.len()))
80+
}
81+
82+
6983
fn bytes_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
7084
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.bytes_type()))]);
7185
let data = get_value(zelf);
@@ -87,8 +101,7 @@ pub fn get_value<'a>(obj: &'a PyObjectRef) -> impl Deref<Target = Vec<u8>> + 'a
87101

88102
fn bytes_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
89103
arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytes_type()))]);
90-
let data = get_value(obj);
91-
let data: Vec<String> = data.iter().map(|b| format!("\\x{:02x}", b)).collect();
92-
let data = data.join("");
104+
let value = get_value(obj);
105+
let data = String::from_utf8(value.to_vec()).unwrap();
93106
Ok(vm.new_str(format!("b'{}'", data)))
94107
}

0 commit comments

Comments
 (0)