Skip to content

Commit ee4c242

Browse files
authored
Merge pull request #1528 from zack-dev-cm/fix/empty-slice-write-indexerror
Restore IndexError for oversized empty slice writes
2 parents 39319c8 + 32ce7b1 commit ee4c242

2 files changed

Lines changed: 58 additions & 5 deletions

File tree

‎src/netCDF4/utils.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
213213

214214
# replace boolean arrays with sequences of integers.
215215
newElem = []
216+
has_explicit_slice = False
216217
IndexErrorMsg=\
217218
"only integers, slices (`:`), ellipsis (`...`), and 1-d integer or boolean arrays are valid indices"
218219
i=0
@@ -226,7 +227,8 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
226227
except:
227228
raise IndexError(IndexErrorMsg)
228229
# plain integers, slices and ellipsis need no numpy conversion.
229-
simple = type(e) is int or type(e) is slice or e is Ellipsis
230+
index_type = type(e)
231+
simple = index_type is int or index_type is slice or e is Ellipsis
230232
if not simple:
231233
ea = np.asarray(e)
232234
# Raise error if multidimensional indexing is used.
@@ -243,11 +245,13 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
243245
else:
244246
unlim = False
245247
# integer scalar
246-
if type(e) is int:
248+
if index_type is int:
247249
newElem.append(e)
248250
# slice or ellipsis object
249251
elif simple:
250-
if not use_get_vars and type(e) == slice and e.step not in [None,-1,1] and\
252+
# Preserve slice intent across both strided and empty-index conversion.
253+
has_explicit_slice = has_explicit_slice or index_type is slice
254+
if not use_get_vars and index_type is slice and e.step not in [None,-1,1] and\
251255
dimensions is not None and grp is not None:
252256
# convert strided slice to integer sequence if possible
253257
# (this will avoid nc_get_vars, which is slow - issue #680).
@@ -502,6 +506,11 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
502506
indices_[:] = indices
503507
indices = indices_.reshape(compact)
504508

509+
if (empty and put and has_explicit_slice and dimensions is not None and len(dimensions) == 1
510+
and datashape is not None and len(datashape) == 1 and datashape[0] > 1):
511+
# Report the same size mismatch as _put for an oversized slice write.
512+
raise IndexError("size of data array does not conform to slice")
513+
505514
if empty and not put:
506515
# Empty reads bypass native bounds checks, including those for vlens.
507516
for i, e in enumerate(elem):

‎test/test_empty_indexing.py‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
import tempfile
44
import unittest
5+
from collections import UserList
56
from typing import Any
67

78
import numpy as np
@@ -261,13 +262,56 @@ def test_one_dimensional_empty_broadcast(self):
261262
ds.createDimension('x', 3)
262263
variable = ds.createVariable('data', 'i4', ('x',))
263264
variable[:] = [10, 20, 30]
264-
for empty in (EMPTY, slice(0), np.zeros(3, dtype=bool)):
265+
cases = (
266+
(EMPTY, ValueError),
267+
(slice(0), IndexError),
268+
(np.zeros(3, dtype=bool), ValueError),
269+
)
270+
for empty, error in cases:
265271
with self.subTest(empty=repr(empty)):
266272
variable[empty] = np.array([123])
267273
assert_array_equal(variable[:], [10, 20, 30])
268-
with self.assertRaises((ValueError, IndexError)):
274+
with self.assertRaises(error):
269275
variable[empty] = np.array([123, 456])
270276

277+
def test_oversized_empty_slice_write(self):
278+
path = os.path.join(self.directory.name, 'slice-write.nc')
279+
cases = (
280+
(None, slice(-3, None)),
281+
(None, (Ellipsis, slice(-2, -2))),
282+
(None, [slice(-3, None)]),
283+
(2, slice(1, 1)),
284+
(2, UserList([slice(1, 1)])),
285+
)
286+
for length, key in cases:
287+
with self.subTest(length=length, key=key):
288+
with Dataset(path, 'w') as ds:
289+
ds.createDimension('time', length)
290+
variable = ds.createVariable('sensor', 'i4', ('time',))
291+
variable[:] = [0, 1]
292+
with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'):
293+
variable[key] = [9, 8, 7]
294+
variable[:0] = [9]
295+
self.assertEqual(len(ds.dimensions['time']), 2)
296+
self.assertEqual(variable.shape, (2,))
297+
assert_array_equal(variable[:], [0, 1])
298+
299+
def test_oversized_empty_strided_slice_write(self):
300+
path = os.path.join(self.directory.name, 'strided-write.nc')
301+
for use_get_vars in (False, True):
302+
with self.subTest(use_get_vars=use_get_vars):
303+
with Dataset(path, 'w') as ds:
304+
ds.createDimension('time', 2)
305+
variable = ds.createVariable('sensor', 'i4', ('time',))
306+
variable[:] = [0, 1]
307+
variable.use_nc_get_vars(use_get_vars)
308+
with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'):
309+
variable[4:5:2] = [9, 8, 7]
310+
variable[4:5:2] = [9]
311+
self.assertEqual(len(ds.dimensions['time']), 2)
312+
self.assertEqual(variable.shape, (2,))
313+
assert_array_equal(variable[:], [0, 1])
314+
271315
def test_empty_encoded_characters(self):
272316
raw = np.array(['alpha', 'bravo', 'delta', 'gamma'], dtype='S5').view('S1').reshape(4, 5)
273317
paths = []

0 commit comments

Comments
 (0)