Commit 71a80959bf6f51de58540ed9b39b8913ccf5f9ee

Authored by Jürgen Knödlseder
1 parent a9ec30d3

Check for index validity in GSkyMap::__getitem__() method (#1581).

This is needed for correct catching of exceptions by the SWIG interface on some operating systems.
pyext/GSkyMap.i
... ... @@ -183,11 +183,21 @@ public:
183 183 ***************************************************************************/
184 184 %extend GSkyMap {
185 185 double __getitem__(int GSkyMapInx[]) {
  186 + if (GSkyMapInx[1] < 0 || GSkyMapInx[1] >= self->npix()) {
  187 + throw GException::out_of_range("__getitem__(int)", "Sky map index",
  188 + GSkyMapInx[1], self->npix());
  189 + }
186 190 if (GSkyMapInx[0] == 1) {
187 191 return (*self)(GSkyMapInx[1]);
188 192 }
189 193 else {
190   - return (*self)(GSkyMapInx[1], GSkyMapInx[2]);
  194 + if (GSkyMapInx[2] >= 0 && GSkyMapInx[2] < self->nmaps()) {
  195 + return (*self)(GSkyMapInx[1], GSkyMapInx[2]);
  196 + }
  197 + else {
  198 + throw GException::out_of_range("__getitem__(int)", "Sky map number",
  199 + GSkyMapInx[2], self->nmaps());
  200 + }
191 201 }
192 202 }
193 203 /*
... ... @@ -196,11 +206,21 @@ public:
196 206 }
197 207 */
198 208 void __setitem__(int GSkyMapInx[], double value) {
  209 + if (GSkyMapInx[1] < 0 || GSkyMapInx[1] >= self->npix()) {
  210 + throw GException::out_of_range("__setitem__(int)", "Sky map index",
  211 + GSkyMapInx[1], self->npix());
  212 + }
199 213 if (GSkyMapInx[0] == 1) {
200 214 (*self)(GSkyMapInx[1]) = value;
201 215 }
202 216 else {
203   - (*self)(GSkyMapInx[1], GSkyMapInx[2]) = value;
  217 + if (GSkyMapInx[2] >= 0 && GSkyMapInx[2] < self->nmaps()) {
  218 + (*self)(GSkyMapInx[1], GSkyMapInx[2]) = value;
  219 + }
  220 + else {
  221 + throw GException::out_of_range("__setitem__(int)", "Sky map number",
  222 + GSkyMapInx[2], self->nmaps());
  223 + }
204 224 }
205 225 }
206 226 /*
... ...
test/test_GSky.py
... ... @@ -370,6 +370,12 @@ class Test(gammalib.GPythonTestSuite):
370 370 self.test_value(map[1], 3.0)
371 371 self.test_value(map[2], 5.0)
372 372 self.test_value(map[3], 7.0)
  373 +
  374 + # Access operator (tests also proper iteration)
  375 + sum = 0.0
  376 + for pix in map:
  377 + sum += pix
  378 + self.test_value(sum, 16.0)
373 379  
374 380 # Return
375 381 return
... ...