MCPcopy Index your code
hub / github.com/RustPython/RustPython / test_memoryview_cast

Method test_memoryview_cast

Lib/test/test_buffer.py:2704–2762  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

2702 [2**10, 2**10, 2**5, 2**3, 2**1])
2703
2704 def test_memoryview_cast(self):
2705 bytespec = (
2706 ('B', lambda ex: list(ex.tobytes())),
2707 ('b', lambda ex: [x-256 if x > 127 else x for x in list(ex.tobytes())]),
2708 ('c', lambda ex: [bytes(chr(x), 'latin-1') for x in list(ex.tobytes())]),
2709 )
2710
2711 def iter_roundtrip(ex, m, items, fmt):
2712 srcsize = struct.calcsize(fmt)
2713 for bytefmt, to_bytelist in bytespec:
2714
2715 m2 = m.cast(bytefmt)
2716 lst = to_bytelist(ex)
2717 self.verify(m2, obj=ex,
2718 itemsize=1, fmt=bytefmt, readonly=False,
2719 ndim=1, shape=[31*srcsize], strides=(1,),
2720 lst=lst, cast=True)
2721
2722 m3 = m2.cast(fmt)
2723 self.assertEqual(m3, ex)
2724 lst = ex.tolist()
2725 self.verify(m3, obj=ex,
2726 itemsize=srcsize, fmt=fmt, readonly=False,
2727 ndim=1, shape=[31], strides=(srcsize,),
2728 lst=lst, cast=True)
2729
2730 # cast from ndim = 0 to ndim = 1
2731 srcsize = struct.calcsize('I')
2732 ex = ndarray(9, shape=[], format='I')
2733 destitems, destshape = cast_items(ex, 'B', 1)
2734 m = memoryview(ex)
2735 m2 = m.cast('B')
2736 self.verify(m2, obj=ex,
2737 itemsize=1, fmt='B', readonly=True,
2738 ndim=1, shape=destshape, strides=(1,),
2739 lst=destitems, cast=True)
2740
2741 # cast from ndim = 1 to ndim = 0
2742 destsize = struct.calcsize('I')
2743 ex = ndarray([9]*destsize, shape=[destsize], format='B')
2744 destitems, destshape = cast_items(ex, 'I', destsize, shape=[])
2745 m = memoryview(ex)
2746 m2 = m.cast('I', shape=[])
2747 self.verify(m2, obj=ex,
2748 itemsize=destsize, fmt='I', readonly=True,
2749 ndim=0, shape=(), strides=(),
2750 lst=destitems, cast=True)
2751
2752 # array.array: roundtrip to/from bytes
2753 for fmt, items, _ in iter_format(31, 'array'):
2754 ex = array.array(fmt, items)
2755 m = memoryview(ex)
2756 iter_roundtrip(ex, m, items, fmt)
2757
2758 # ndarray: roundtrip to/from bytes
2759 for fmt, items, _ in iter_format(31, 'memoryview'):
2760 ex = ndarray(items, shape=[31], format=fmt, flags=ND_WRITABLE)
2761 m = memoryview(ex)

Callers

nothing calls this directly

Calls 7

verifyMethod · 0.95
listClass · 0.85
chrFunction · 0.85
cast_itemsFunction · 0.85
iter_formatFunction · 0.85
tobytesMethod · 0.45
castMethod · 0.45

Tested by

no test coverage detected