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
17 changes: 17 additions & 0 deletions Lib/test/test_memoryview.py
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,23 @@ def test_picklebuffer_reference_loop(self):
gc.collect()
self.assertIsNone(wr())

def test_overflows_in_floats(self):
array = import_helper.import_module("array")
half_data = array.array('e', [0.0])
float_data = array.array('f', [0.0])
complex_data = array.array('Zf', [0.0])
half_view = memoryview(half_data)
float_view = memoryview(float_data)
complex_view = memoryview(complex_data)
with self.assertRaises(ValueError):
half_view[0] = 123456.0
with self.assertRaises(ValueError):
float_view[0] = 1e300
with self.assertRaises(ValueError):
complex_view[0] = 1e300
with self.assertRaises(ValueError):
complex_view[0] = 1e300j


@threading_helper.requires_working_threading()
@support.requires_resource("cpu")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Raise :exc:`ValueError`'s for overflows, while trying to change
:class:`memoryview` elements with ``'f'`` and ``'Zf'`` format codes. Patch
by Sergey B Kirpichev.
13 changes: 9 additions & 4 deletions Objects/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2037,7 +2037,9 @@ pack_single(PyMemoryViewObject *self, char *ptr, PyObject *item, const char *fmt
goto err_occurred;
CHECK_RELEASED_INT_AGAIN(self);
if (fmt[0] == 'f') {
PACK_SINGLE(ptr, d, float);
if (PyFloat_Pack4(d, ptr, endian) < 0) {
goto err_occurred;
}
}
else if (fmt[0] == 'd') {
PACK_SINGLE(ptr, d, double);
Expand All @@ -2064,9 +2066,12 @@ pack_single(PyMemoryViewObject *self, char *ptr, PyObject *item, const char *fmt
memcpy(ptr, &x, sizeof(x));
}
else {
float x[2] = {(float)c.real, (float)c.imag};

memcpy(ptr, &x, sizeof(x));
if (PyFloat_Pack4(c.real, ptr, endian) < 0) {
goto err_occurred;
}
if (PyFloat_Pack4(c.imag, ptr + sizeof(float), endian) < 0) {
goto err_occurred;
}
}
break;

Expand Down
Loading