Skip to content
Merged
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
15 changes: 12 additions & 3 deletions src/netCDF4/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\

# replace boolean arrays with sequences of integers.
newElem = []
has_explicit_slice = False
IndexErrorMsg=\
"only integers, slices (`:`), ellipsis (`...`), and 1-d integer or boolean arrays are valid indices"
i=0
Expand All @@ -226,7 +227,8 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
except:
raise IndexError(IndexErrorMsg)
# plain integers, slices and ellipsis need no numpy conversion.
simple = type(e) is int or type(e) is slice or e is Ellipsis
index_type = type(e)
simple = index_type is int or index_type is slice or e is Ellipsis
if not simple:
ea = np.asarray(e)
# Raise error if multidimensional indexing is used.
Expand All @@ -243,11 +245,13 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
else:
unlim = False
# integer scalar
if type(e) is int:
if index_type is int:
newElem.append(e)
# slice or ellipsis object
elif simple:
if not use_get_vars and type(e) == slice and e.step not in [None,-1,1] and\
# Preserve slice intent across both strided and empty-index conversion.
has_explicit_slice = has_explicit_slice or index_type is slice
if not use_get_vars and index_type is slice and e.step not in [None,-1,1] and\
dimensions is not None and grp is not None:
# convert strided slice to integer sequence if possible
# (this will avoid nc_get_vars, which is slow - issue #680).
Expand Down Expand Up @@ -502,6 +506,11 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
indices_[:] = indices
indices = indices_.reshape(compact)

if (empty and put and has_explicit_slice and dimensions is not None and len(dimensions) == 1
and datashape is not None and len(datashape) == 1 and datashape[0] > 1):
# Report the same size mismatch as _put for an oversized slice write.
raise IndexError("size of data array does not conform to slice")

if empty and not put:
# Empty reads bypass native bounds checks, including those for vlens.
for i, e in enumerate(elem):
Expand Down
48 changes: 46 additions & 2 deletions test/test_empty_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import tempfile
import unittest
from collections import UserList
from typing import Any

import numpy as np
Expand Down Expand Up @@ -261,13 +262,56 @@ def test_one_dimensional_empty_broadcast(self):
ds.createDimension('x', 3)
variable = ds.createVariable('data', 'i4', ('x',))
variable[:] = [10, 20, 30]
for empty in (EMPTY, slice(0), np.zeros(3, dtype=bool)):
cases = (
(EMPTY, ValueError),
(slice(0), IndexError),
(np.zeros(3, dtype=bool), ValueError),
)
for empty, error in cases:
with self.subTest(empty=repr(empty)):
variable[empty] = np.array([123])
assert_array_equal(variable[:], [10, 20, 30])
with self.assertRaises((ValueError, IndexError)):
with self.assertRaises(error):
variable[empty] = np.array([123, 456])

def test_oversized_empty_slice_write(self):
path = os.path.join(self.directory.name, 'slice-write.nc')
cases = (
(None, slice(-3, None)),
(None, (Ellipsis, slice(-2, -2))),
(None, [slice(-3, None)]),
(2, slice(1, 1)),
(2, UserList([slice(1, 1)])),
)
for length, key in cases:
with self.subTest(length=length, key=key):
with Dataset(path, 'w') as ds:
ds.createDimension('time', length)
variable = ds.createVariable('sensor', 'i4', ('time',))
variable[:] = [0, 1]
with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'):
variable[key] = [9, 8, 7]
variable[:0] = [9]
self.assertEqual(len(ds.dimensions['time']), 2)
self.assertEqual(variable.shape, (2,))
assert_array_equal(variable[:], [0, 1])

def test_oversized_empty_strided_slice_write(self):
path = os.path.join(self.directory.name, 'strided-write.nc')
for use_get_vars in (False, True):
with self.subTest(use_get_vars=use_get_vars):
with Dataset(path, 'w') as ds:
ds.createDimension('time', 2)
variable = ds.createVariable('sensor', 'i4', ('time',))
variable[:] = [0, 1]
variable.use_nc_get_vars(use_get_vars)
with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'):
variable[4:5:2] = [9, 8, 7]
variable[4:5:2] = [9]
self.assertEqual(len(ds.dimensions['time']), 2)
self.assertEqual(variable.shape, (2,))
assert_array_equal(variable[:], [0, 1])

def test_empty_encoded_characters(self):
raw = np.array(['alpha', 'bravo', 'delta', 'gamma'], dtype='S5').view('S1').reshape(4, 5)
paths = []
Expand Down
Loading