• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
23 /* T must be integer type, den must not be 0 */
24 template<class T>
divRound(const T & nom,const T & den)25 inline static const T divRound(const T &nom, const T &den) {
26     if ((nom >= 0) ^ (den >= 0)) {
27         return (nom - den / 2) / den;
28     } else {
29         return (nom + den / 2) / den;
30     }
31 }
32 
33 /* == ceil(nom / den). T must be integer type, den must not be 0 */
34 template<class T>
divUp(const T & nom,const T & den)35 inline static const T divUp(const T &nom, const T &den) {
36     if (den < 0) {
37         return (nom < 0 ? nom + den + 1 : nom) / den;
38     } else {
39         return (nom < 0 ? nom : nom + den - 1) / den;
40     }
41 }
42 
43 template<class T>
abs(const T & a)44 inline static T abs(const T &a) {
45     return a < 0 ? -a : a;
46 }
47 
48 template<class T>
min(const T & a,const T & b)49 inline static const T &min(const T &a, const T &b) {
50     return a < b ? a : b;
51 }
52 
53 template<class T>
max(const T & a,const T & b)54 inline static const T &max(const T &a, const T &b) {
55     return a > b ? a : b;
56 }
57 
58 /* T must be integer type, period must be positive */
59 template<class T>
periodicError(const T & val,const T & period)60 inline static T periodicError(const T &val, const T &period) {
61     T err = abs(val) % period;
62     return (err < (period / 2)) ? err : (period - err);
63 }
64 
65 #endif  // A_UTILS_H_
66