Skip to content

Commit c0e4ea8

Browse files
committed
Merge pull request #325 from matthew-brett/img-size-fix
BUG: work round int overflow in size calculation
2 parents 368c407 + 4999e50 commit c0e4ea8

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

nibabel/tests/test_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1227,3 +1227,21 @@ def assert_rt(data,
12271227
slope = slope,
12281228
post_clips = post_clips,
12291229
nan_fill = nan_fill)
1230+
1231+
1232+
def test_array_from_file_overflow():
1233+
# Test for int overflow in size calculation in array_from_file
1234+
shape = (1500,) * 6
1235+
class NoStringIO: # Null file-like for forcing error
1236+
def seek(self, n_bytes):
1237+
pass
1238+
def read(self, n_bytes):
1239+
return b''
1240+
try:
1241+
array_from_file(shape, np.int8, NoStringIO())
1242+
except IOError as err:
1243+
message = str(err)
1244+
assert_equal(message,
1245+
'Expected {0} bytes, got {1} bytes from {2}\n'
1246+
' - could the file be damaged?'.format(
1247+
11390625000000000000, 0, 'object'))

nibabel/volumeutils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import gzip
1515
import bz2
1616
from os.path import exists, splitext
17+
from operator import mul
18+
from functools import reduce
1719

1820
import numpy as np
1921

@@ -504,7 +506,8 @@ def array_from_file(shape, in_dtype, infile, offset=0, order='F', mmap=True):
504506
pass
505507
if len(shape) == 0:
506508
return np.array([])
507-
n_bytes = int(np.prod(shape) * in_dtype.itemsize)
509+
# Use reduce and mul to work around numpy integer overflow
510+
n_bytes = reduce(mul, shape) * in_dtype.itemsize
508511
if n_bytes == 0:
509512
return np.array([])
510513
# Read data from file

0 commit comments

Comments
 (0)