Skip to content

Commit 2f891fa

Browse files
committed
NF+TST - add test for fit of shape to header dtype
Previously, setting shapes greater than Analyze type headers would allow would result in silent overflow. Add check and test.
1 parent f069bb9 commit 2f891fa

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

nibabel/analyze.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,10 @@ def set_data_shape(self, shape):
635635
dims[:] = 1
636636
dims[0] = ndims
637637
dims[1:ndims+1] = shape
638+
# Check that dimensions fit
639+
if not np.all(dims[1:ndims+1] == shape):
640+
raise HeaderDataError('shape %s does not fit in dim datatype' %
641+
shape)
638642
self._structarr['pixdim'][ndims+1:] = 1.0
639643

640644
def get_base_affine(self):

nibabel/tests/test_analyze.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from ..nifti1 import Nifti1Header
2626
from ..loadsave import read_img_data
2727
from .. import imageglobals
28+
from ..casting import as_int
2829

2930
from numpy.testing import (assert_array_equal,
3031
assert_array_almost_equal)
@@ -217,6 +218,22 @@ def test_data_dtype(self):
217218
hdr.set_data_dtype,
218219
inp)
219220

221+
def test_shapes(self):
222+
# Test that shape checks work
223+
hdr = self.header_class()
224+
for shape in ((2, 3, 4), (2, 3, 4, 5), (2, 3), (2,)):
225+
hdr.set_data_shape(shape)
226+
assert_equal(hdr.get_data_shape(), shape)
227+
# Check max works, but max+1 raises error
228+
dim_dtype = hdr.structarr['dim'].dtype
229+
# as_int for safety to deal with numpy 1.4.1 int conversion errors
230+
mx = as_int(np.iinfo(dim_dtype).max)
231+
shape = (mx,)
232+
hdr.set_data_shape(shape)
233+
assert_equal(hdr.get_data_shape(), shape)
234+
shape = (mx+1,)
235+
assert_raises(HeaderDataError, hdr.set_data_shape, shape)
236+
220237
def test_read_write_data(self):
221238
# Check reading and writing of data
222239
hdr = self.header_class()

0 commit comments

Comments
 (0)