main.c (2053B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 #include "stdlib/ndarray/base/ind.h" 20 #include "stdlib/ndarray/index_modes.h" 21 #include "stdlib/ndarray/base/wrap_index.h" 22 #include "stdlib/ndarray/base/clamp_index.h" 23 #include <stdint.h> 24 25 /** 26 * Returns an index given an index mode. 27 * 28 * ## Notes 29 * 30 * - The function returns `-1` if an index is out-of-bounds. 31 * 32 * @param idx index 33 * @param max maximum index (should be nonnegative) 34 * @param mode index mode specifying how to handle an index outside the interval `[0,max]` 35 * @return index 36 * 37 * @example 38 * #include "stdlib/ndarray/index_modes.h" 39 * #include "stdlib/ndarray/base/ind.h" 40 * 41 * int64_t idx = stdlib_ndarray_ind( 10, 8, STDLIB_NDARRAY_INDEX_CLAMP ); 42 * // returns 8 43 * 44 * @example 45 * #include "stdlib/ndarray/index_modes.h" 46 * #include "stdlib/ndarray/base/ind.h" 47 * 48 * int64_t idx = stdlib_ndarray_ind( 13, 10, STDLIB_NDARRAY_INDEX_WRAP ); 49 * // returns 2 50 * 51 * @example 52 * #include "stdlib/ndarray/index_modes.h" 53 * #include "stdlib/ndarray/base/ind.h" 54 * 55 * int64_t idx = stdlib_ndarray_ind( 10, 8, STDLIB_NDARRAY_INDEX_ERROR ); 56 * // returns -1 57 */ 58 int64_t stdlib_ndarray_ind( const int64_t idx, const int64_t max, const enum STDLIB_NDARRAY_INDEX_MODE mode ) { 59 if ( mode == STDLIB_NDARRAY_INDEX_CLAMP ) { 60 return stdlib_ndarray_clamp_index( idx, max ); 61 } 62 if ( mode == STDLIB_NDARRAY_INDEX_WRAP ) { 63 return stdlib_ndarray_wrap_index( idx, max ); 64 } 65 if ( idx < 0 || idx > max ) { 66 return -1; // out-of-bounds 67 } 68 return idx; 69 }