Skip to content

Commit 638f600

Browse files
morealCopilot
authored andcommitted
Implement bytearray.__str__ && bytes.__str__ (#7477)
* Implement bytearray.__str__ * Implement bytes.__str__ * Turn __str__ method into slot
1 parent 7d3cee9 commit 638f600

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

crates/vm/src/builtins/bytearray.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,15 @@ impl PyByteArray {
215215
size_of::<Self>() + self.borrow_buf().len() * size_of::<u8>()
216216
}
217217

218+
#[pyslot]
219+
fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
220+
let zelf = zelf.downcast_ref::<Self>().expect("expected bytearray");
221+
PyBytesInner::warn_on_str("str() on a bytearray instance", vm)?;
222+
let class_name = zelf.class().name();
223+
let repr = zelf.inner().repr_with_name(&class_name, vm)?;
224+
Ok(vm.ctx.new_str(repr))
225+
}
226+
218227
fn __add__(&self, other: ArgBytesLike) -> Self {
219228
self.inner().add(&other.borrow_buf()).into()
220229
}

crates/vm/src/builtins/bytes.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,13 @@ impl PyBytes {
224224
size_of::<Self>() + self.len() * size_of::<u8>()
225225
}
226226

227+
#[pyslot]
228+
fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
229+
let zelf = zelf.downcast_ref::<Self>().expect("expected bytes");
230+
PyBytesInner::warn_on_str("str() on a bytes instance", vm)?;
231+
Ok(vm.ctx.new_str(zelf.inner.repr_bytes(vm)?))
232+
}
233+
227234
fn __add__(&self, other: ArgBytesLike) -> Vec<u8> {
228235
self.inner.add(&other.borrow_buf())
229236
}

crates/vm/src/bytes_inner.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,18 @@ impl PyBytesInner {
237237
vm.new_overflow_error("bytes object is too large to make repr")
238238
}
239239

240+
pub(crate) fn warn_on_str(message: &'static str, vm: &VirtualMachine) -> PyResult<()> {
241+
if vm.state.config.settings.bytes_warning > 0 {
242+
crate::stdlib::_warnings::warn(
243+
vm.ctx.exceptions.bytes_warning,
244+
message.to_owned(),
245+
1,
246+
vm,
247+
)?;
248+
}
249+
Ok(())
250+
}
251+
240252
pub fn repr_with_name(&self, class_name: &str, vm: &VirtualMachine) -> PyResult<String> {
241253
const DECORATION_LEN: isize = 2 + 3; // 2 for (), 3 for b"" => bytearray(b"")
242254
let escape = crate::literal::escape::AsciiEscape::new_repr(&self.elements);

0 commit comments

Comments
 (0)