diff --git a/crates/vm/src/builtins/bytearray.rs b/crates/vm/src/builtins/bytearray.rs index dec5cacc97..0285526692 100644 --- a/crates/vm/src/builtins/bytearray.rs +++ b/crates/vm/src/builtins/bytearray.rs @@ -215,6 +215,15 @@ impl PyByteArray { size_of::() + self.borrow_buf().len() * size_of::() } + #[pyslot] + fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { + let zelf = zelf.downcast_ref::().expect("expected bytearray"); + PyBytesInner::warn_on_str("str() on a bytearray instance", vm)?; + let class_name = zelf.class().name(); + let repr = zelf.inner().repr_with_name(&class_name, vm)?; + Ok(vm.ctx.new_str(repr)) + } + fn __add__(&self, other: ArgBytesLike) -> Self { self.inner().add(&other.borrow_buf()).into() } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index 9e5d7d0ae5..00cf3d2d11 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -224,6 +224,13 @@ impl PyBytes { size_of::() + self.len() * size_of::() } + #[pyslot] + fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { + let zelf = zelf.downcast_ref::().expect("expected bytes"); + PyBytesInner::warn_on_str("str() on a bytes instance", vm)?; + Ok(vm.ctx.new_str(zelf.inner.repr_bytes(vm)?)) + } + fn __add__(&self, other: ArgBytesLike) -> Vec { self.inner.add(&other.borrow_buf()) } diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index 2318415f0f..6a1aa73c6b 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -237,6 +237,18 @@ impl PyBytesInner { vm.new_overflow_error("bytes object is too large to make repr") } + pub(crate) fn warn_on_str(message: &'static str, vm: &VirtualMachine) -> PyResult<()> { + if vm.state.config.settings.bytes_warning > 0 { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.bytes_warning, + message.to_owned(), + 1, + vm, + )?; + } + Ok(()) + } + pub fn repr_with_name(&self, class_name: &str, vm: &VirtualMachine) -> PyResult { const DECORATION_LEN: isize = 2 + 3; // 2 for (), 3 for b"" => bytearray(b"") let escape = crate::literal::escape::AsciiEscape::new_repr(&self.elements);