normalize index returns true if 'index' is in range: [0..array_len] false otherwise idx is 0-based when non-negative or from the end of the list when negative
| 200 | // idx is 0-based when non-negative |
| 201 | // or from the end of the list when negative |
| 202 | static inline bool normalize_index |
| 203 | ( |
| 204 | int32_t *index, |
| 205 | int32_t arrayLen, |
| 206 | bool bounds_inclusive |
| 207 | ) { |
| 208 | int32_t idx = *index; |
| 209 | |
| 210 | if(bounds_inclusive) { |
| 211 | // for the index normalization calculation to be correct when index is negative |
| 212 | // for example index -1 on a 6 elements array should return the last |
| 213 | // element index |
| 214 | // [0,1,2,3,4,5][-1] = 5 |
| 215 | arrayLen += 1; |
| 216 | } |
| 217 | |
| 218 | //-------------------------------------------------------------------------- |
| 219 | // check index bounds |
| 220 | //-------------------------------------------------------------------------- |
| 221 | |
| 222 | // index range can be [-arrayLen, arrayLen) |
| 223 | // this is because 0 = arrayLen+(-arrayLen) |
| 224 | if((idx < 0 && idx + arrayLen < 0) || |
| 225 | (idx > 0 && idx >= arrayLen)) { |
| 226 | return false; |
| 227 | } |
| 228 | |
| 229 | // compute index |
| 230 | if(idx < 0) { |
| 231 | *index = arrayLen + idx; |
| 232 | } |
| 233 | |
| 234 | // index within bounds |
| 235 | return true; |
| 236 | } |
| 237 | |
| 238 | // If given an array, returns a value in a specific index in an array. |
| 239 | // Valid index range is [-arrayLen, arrayLen). |
no outgoing calls
no test coverage detected