Skip to content

Commit dcca305

Browse files
committed
memoryview hex
1 parent 1d2d8ea commit dcca305

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

Lib/test/test_memoryview.py

-2
Original file line numberDiff line numberDiff line change
@@ -544,8 +544,6 @@ def test_ctypes_cast(self):
544544
m[2:] = memoryview(p6).cast(format)[2:]
545545
self.assertEqual(d.value, 0.6)
546546

547-
# TODO: RUSTPYTHON
548-
@unittest.expectedFailure
549547
def test_memoryview_hex(self):
550548
# Issue #9951: memoryview.hex() segfaults with non-contiguous buffers.
551549
x = b'0' * 200000

vm/src/obj/objbytes.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -222,8 +222,10 @@ impl PyBytes {
222222
self.inner.swapcase().into()
223223
}
224224

225+
// TODO: Changed in version 3.8: bytes.hex() now supports optional sep and
226+
// bytes_per_sep parameters to insert separators between bytes in the hex output.
225227
#[pymethod(name = "hex")]
226-
fn hex(&self) -> String {
228+
pub(crate) fn hex(&self) -> String {
227229
self.inner.hex()
228230
}
229231

vm/src/obj/objmemory.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,30 @@ impl PyMemoryView {
603603
}
604604
}
605605

606+
// TODO: Changed in version 3.8: memoryview.hex() now supports optional sep and bytes_per_sep
607+
// parameters to insert separators between bytes in the hex output.
608+
#[pymethod]
609+
fn hex(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
610+
zelf.try_not_released(vm)?;
611+
let guard;
612+
let vec;
613+
let bytes = match zelf.as_contiguous() {
614+
Some(bytes) => {
615+
guard = bytes;
616+
&*guard
617+
}
618+
None => {
619+
vec = zelf.to_contiguous();
620+
vec.as_slice()
621+
}
622+
};
623+
let s = bytes
624+
.iter()
625+
.map(|x| format!("{:02x}", x))
626+
.collect::<String>();
627+
Ok(s)
628+
}
629+
606630
fn eq(zelf: &PyRef<Self>, other: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
607631
if zelf.is(other) {
608632
return Ok(true);
@@ -686,7 +710,8 @@ impl Buffer for PyMemoryViewRef {
686710
}
687711

688712
fn is_resizable(&self) -> bool {
689-
self.buffer.is_resizable()
713+
// memoryview cannot resize
714+
false
690715
}
691716

692717
fn as_contiguous(&self) -> Option<BorrowedValue<[u8]>> {

0 commit comments

Comments
 (0)