Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Lib/test/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1569,6 +1569,22 @@ def test_byteswap(self):
b.byteswap()
self.assertEqual(a, b)

def test_byteswap_single_call_result(self):
# A single byteswap() must swap each item's two halves (real,
# imag) independently. test_byteswap above only checks that
# byteswap() twice round-trips to the original, which passes
# even if a single call scrambles multi-item arrays.
a = array.array(self.typecode, self.example)
original = a.tobytes()
a.byteswap()
itemsize = a.itemsize
half = itemsize // 2
expected = bytearray()
for i in range(0, len(original), itemsize):
item = original[i:i + itemsize]
expected += item[half - 1::-1] + item[itemsize - 1:half - 1:-1]
self.assertEqual(a.tobytes(), bytes(expected))


class HalfFloatTest(FPTest, unittest.TestCase):
example = [-42.0, 0, 42, 1e2, -1e4]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :meth:`array.array.byteswap` corrupting data for ``'Zd'`` (complex
double) arrays with more than one element: the 16-byte item loop advanced
the buffer pointer by only 8 bytes per iteration, causing items after the
first to be scrambled.
2 changes: 1 addition & 1 deletion Modules/arraymodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1617,7 +1617,7 @@ array_array_byteswap_impl(arrayobject *self)
break;
case 16:
assert(strcmp(self->ob_descr->typecode, "Zd") == 0);
for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 16) {
char t0 = p[0];
char t1 = p[1];
char t2 = p[2];
Expand Down
Loading