forked from Rust-related/RustPython
Add support for __bytes__ method
This commit is contained in:
@@ -614,3 +614,9 @@ assert b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97'.decode('utf-8') == '中文字'
|
||||
# mod
|
||||
assert b'rust%bpython%b' % (b' ', b'!') == b'rust python!'
|
||||
assert b'x=%i y=%f' % (1, 2.5) == b'x=1 y=2.500000'
|
||||
|
||||
class A:
|
||||
def __bytes__(self):
|
||||
return b"bytess"
|
||||
|
||||
assert bytes(A()) == b"bytess"
|
||||
|
||||
@@ -86,15 +86,20 @@ impl ByteInnerNewOptions {
|
||||
);
|
||||
}
|
||||
obj => {
|
||||
// TODO: only support this method in the bytes() constructor
|
||||
if let Some(bytes_method) = vm.get_method(obj.clone(), "__bytes__") {
|
||||
let bytes = vm.invoke(&bytes_method?, vec![])?;
|
||||
return PyByteInner::try_from_object(vm, bytes);
|
||||
}
|
||||
let elements = vm.extract_elements(&obj).or_else(|_| {
|
||||
Err(vm.new_type_error(format!(
|
||||
"cannot convert '{}' object to bytes",
|
||||
obj.class().name
|
||||
)))
|
||||
});
|
||||
})?;
|
||||
|
||||
let mut data_bytes = vec![];
|
||||
for elem in elements? {
|
||||
for elem in elements {
|
||||
let v = objint::to_int(vm, &elem, &BigInt::from(10))?;
|
||||
if let Some(i) = v.to_u8() {
|
||||
data_bytes.push(i);
|
||||
|
||||
Reference in New Issue
Block a user