Author: Richard Plangger <planri...@gmail.com> Branch: py3.5-memoryview Changeset: r86212:8e69fe818876 Date: 2016-08-16 11:13 +0200 http://bitbucket.org/pypy/pypy/changeset/8e69fe818876/
Log: hex method for memoryview + tests diff --git a/pypy/objspace/std/bytearrayobject.py b/pypy/objspace/std/bytearrayobject.py --- a/pypy/objspace/std/bytearrayobject.py +++ b/pypy/objspace/std/bytearrayobject.py @@ -491,6 +491,24 @@ i += 2 return data +HEXDIGITS = "0123456789abcdef" +PY_SIZE_T_MAX = 2**(rffi.sizeof(rffi.SIZE_T)*8)-1 + +def _array_to_hexstring(space, buf): + length = buf.getlength() + hexstring = StringBuilder(length*2) + + if length > PY_SIZE_T_MAX/2: + raise OperationError(space.w_MemoryError) + + for i in range(length): + byte = ord(buf.getitem(i)) + c = (byte >> 4 & 0xf) + hexstring.append(HEXDIGITS[c]) + c = (byte & 0xf) + hexstring.append(HEXDIGITS[c]) + + return space.wrap(hexstring.build()) class BytearrayDocstrings: """bytearray(iterable_of_ints) -> bytearray diff --git a/pypy/objspace/std/memoryobject.py b/pypy/objspace/std/memoryobject.py --- a/pypy/objspace/std/memoryobject.py +++ b/pypy/objspace/std/memoryobject.py @@ -232,6 +232,11 @@ newitemsize = self.get_native_fmtchar(fmt) return W_MemoryView(self.buf, fmt, newitemsize) + def descr_hex(self, space): + from pypy.objspace.std.bytearrayobject import _array_to_hexstring + self._check_released(space) + return _array_to_hexstring(space, self.buf) + W_MemoryView.typedef = TypeDef( "memoryview", @@ -250,6 +255,7 @@ __exit__ = interp2app(W_MemoryView.descr_exit), __weakref__ = make_weakref_descr(W_MemoryView), cast = interp2app(W_MemoryView.descr_cast), + hex = interp2app(W_MemoryView.descr_hex), tobytes = interp2app(W_MemoryView.descr_tobytes), tolist = interp2app(W_MemoryView.descr_tolist), release = interp2app(W_MemoryView.descr_release), diff --git a/pypy/objspace/std/test/test_memoryobject.py b/pypy/objspace/std/test/test_memoryobject.py --- a/pypy/objspace/std/test/test_memoryobject.py +++ b/pypy/objspace/std/test/test_memoryobject.py @@ -18,6 +18,7 @@ assert len(w) == 2 exc = raises(NotImplementedError, "v[0:2:2]") assert str(exc.value) == "" + exc = raises(TypeError, "memoryview('foobar')") def test_rw(self): data = bytearray(b'abcefg') @@ -161,3 +162,6 @@ raises(ValueError, memoryview(b"foobar")._pypy_raw_address) a = memoryview(bytearray(b"foobar"))._pypy_raw_address() assert a != 0 + + def test_hex(self): + assert memoryview(b"abc").hex() == u'616263' _______________________________________________ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit