Skip to content

Commit cb51ca8

Browse files
committed
memoryview hex
1 parent f6a5e8d commit cb51ca8

File tree

4 files changed

+29
-6
lines changed

4 files changed

+29
-6
lines changed

Lib/test/test_bytes.py

-2
Original file line numberDiff line numberDiff line change
@@ -416,8 +416,6 @@ def test_fromhex(self):
416416
self.type2test.fromhex(data)
417417
self.assertIn('at position %s' % pos, str(cm.exception))
418418

419-
# TODO: RUSTPYTHON
420-
@unittest.expectedFailure
421419
def test_hex(self):
422420
self.assertRaises(TypeError, self.type2test.hex)
423421
self.assertRaises(TypeError, self.type2test.hex, 1)

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
@@ -221,8 +221,10 @@ impl PyBytes {
221221
self.inner.swapcase().into()
222222
}
223223

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

vm/src/obj/objmemory.rs

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

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

687711
fn is_resizable(&self) -> bool {
688-
self.buffer.is_resizable()
712+
// memoryview cannot resize
713+
false
689714
}
690715

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

0 commit comments

Comments
 (0)