Skip to content

Commit 07ff469

Browse files
committed
Implement bytearray.mod
Implement bytearray formatting with CFormat
1 parent 8267ea4 commit 07ff469

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

tests/snippets/bytearray.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,3 +706,7 @@
706706
assert a == bytearray(b'\x00testt')
707707
a[:6] = memoryview(b'test')
708708
assert a == bytearray(b'test')
709+
710+
# mod
711+
assert bytearray('rust%bpython%b', 'utf-8') % (b' ', b'!') == bytearray(b'rust python!')
712+
assert bytearray('x=%i y=%f', 'utf-8') % (1, 2.5) == bytearray(b'x=1 y=2.500000')

vm/src/obj/objbytearray.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,16 @@ use super::objslice::PySliceRef;
1313
use super::objstr::PyStringRef;
1414
use super::objtuple::PyTupleRef;
1515
use super::objtype::PyClassRef;
16+
use crate::cformat::CFormatString;
1617
use crate::function::OptionalArg;
18+
use crate::obj::objstr::do_cformat_string;
1719
use crate::pyobject::{
1820
Either, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
1921
TryFromObject,
2022
};
2123
use crate::vm::VirtualMachine;
2224
use std::mem::size_of;
25+
use std::str::FromStr;
2326

2427
/// "bytearray(iterable_of_ints) -> bytearray\n\
2528
/// bytearray(string, encoding[, errors]) -> bytearray\n\
@@ -557,6 +560,31 @@ impl PyByteArrayRef {
557560
self.inner.borrow_mut().irepeat(n, vm)
558561
}
559562

563+
fn do_cformat(
564+
&self,
565+
vm: &VirtualMachine,
566+
format_string: CFormatString,
567+
values_obj: PyObjectRef,
568+
) -> PyResult {
569+
let final_string = do_cformat_string(vm, format_string, values_obj)?;
570+
Ok(vm
571+
.ctx
572+
.new_bytearray(PyByteInner::from_string(final_string.as_str(), "utf8", vm)?.elements))
573+
}
574+
575+
#[pymethod(name = "__mod__")]
576+
fn modulo(self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult {
577+
let format_string =
578+
CFormatString::from_str(std::str::from_utf8(&self.inner.borrow().elements).unwrap())
579+
.map_err(|err| vm.new_value_error(err.to_string()))?;
580+
self.do_cformat(vm, format_string, values.clone())
581+
}
582+
583+
#[pymethod(name = "__rmod__")]
584+
fn rmod(self, _values: PyObjectRef, vm: &VirtualMachine) -> PyResult {
585+
Ok(vm.ctx.not_implemented())
586+
}
587+
560588
#[pymethod(name = "reverse")]
561589
fn reverse(self, _vm: &VirtualMachine) -> PyResult<()> {
562590
self.inner.borrow_mut().elements.reverse();

0 commit comments

Comments
 (0)