Skip to content

Commit d5b0965

Browse files
committed
Implement bytearray.decode
1 parent 7ab9a64 commit d5b0965

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

vm/src/obj/objbytearray.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@ use super::objbyteinner::{
1010
use super::objint::PyIntRef;
1111
use super::objiter;
1212
use super::objslice::PySliceRef;
13-
use super::objstr::PyStringRef;
13+
use super::objstr::{PyString, PyStringRef};
1414
use super::objtuple::PyTupleRef;
1515
use super::objtype::PyClassRef;
1616
use crate::cformat::CFormatString;
1717
use crate::function::OptionalArg;
1818
use crate::obj::objstr::do_cformat_string;
1919
use crate::pyobject::{
2020
Either, PyClassImpl, PyComparisonValue, PyContext, PyIterable, PyObjectRef, PyRef, PyResult,
21-
PyValue, TryFromObject,
21+
PyValue, TryFromObject, TypeProtocol,
2222
};
2323
use crate::vm::VirtualMachine;
2424
use std::mem::size_of;
@@ -590,6 +590,26 @@ impl PyByteArray {
590590
self.inner.borrow_mut().elements.reverse();
591591
Ok(())
592592
}
593+
594+
#[pymethod]
595+
fn decode(
596+
zelf: PyRef<Self>,
597+
encoding: OptionalArg<PyStringRef>,
598+
errors: OptionalArg<PyStringRef>,
599+
vm: &VirtualMachine,
600+
) -> PyResult<PyStringRef> {
601+
let encoding = encoding.into_option();
602+
vm.decode(zelf.into_object(), encoding.clone(), errors.into_option())?
603+
.downcast::<PyString>()
604+
.map_err(|obj| {
605+
vm.new_type_error(format!(
606+
"'{}' decoder returned '{}' instead of 'str'; use codecs.encode() to \
607+
encode arbitrary types",
608+
encoding.as_ref().map_or("utf-8", |s| s.as_str()),
609+
obj.class().name,
610+
))
611+
})
612+
}
593613
}
594614

595615
// fn set_value(obj: &PyObjectRef, value: Vec<u8>) {

0 commit comments

Comments
 (0)