AUtils.h revision 67a30ebfe785f7cd5ecfb0d2fb487e54536a3d48
1/* 2 * Copyright 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifndef A_UTILS_H_ 18 19#define A_UTILS_H_ 20 21/* ============================ math templates ============================ */ 22 23template<class T> 24void ENSURE_UNSIGNED_TYPE() { 25 T TYPE_MUST_BE_UNSIGNED[(T)-1 < 0 ? -1 : 0]; 26} 27 28// needle is in range [hayStart, hayStart + haySize) 29template<class T, class U> 30inline static bool isInRange(const T &hayStart, const U &haySize, const T &needle) { 31 ENSURE_UNSIGNED_TYPE<U>(); 32 return (T)(hayStart + haySize) >= hayStart && needle >= hayStart && (U)(needle - hayStart) < haySize; 33} 34 35// [needleStart, needleStart + needleSize) is in range [hayStart, hayStart + haySize) 36template<class T, class U> 37inline static bool isInRange( 38 const T &hayStart, const U &haySize, const T &needleStart, const U &needleSize) { 39 ENSURE_UNSIGNED_TYPE<U>(); 40 return isInRange(hayStart, haySize, needleStart) 41 && (T)(needleStart + needleSize) >= needleStart 42 && (U)(needleStart + needleSize - hayStart) <= haySize; 43} 44 45#endif // A_UTILS_H_ 46