1 // Copyright (C) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef ICING_UTIL_MATH_UTIL_H_
16 #define ICING_UTIL_MATH_UTIL_H_
17
18 #include <limits>
19
20 namespace icing {
21 namespace lib {
22
23 namespace math_util {
24
SafeDivide(double first,double second)25 inline double SafeDivide(double first, double second) {
26 if (second == 0) {
27 return std::numeric_limits<double>::infinity();
28 }
29 return first / second;
30 }
31
32 // Returns the maximum integer value which is a multiple of rounding_value,
33 // and less than or equal to input_value.
34 //
35 // input_value must be greater than or equal to zero, or else returns 0.
36 // rounding_value must be greater than or equal to zero, or else returns 0.
37 template <typename IntType>
RoundDownTo(IntType input_value,IntType rounding_value)38 static IntType RoundDownTo(IntType input_value, IntType rounding_value) {
39 static_assert(std::numeric_limits<IntType>::is_integer,
40 "RoundDownTo() operation type is not integer");
41
42 if (input_value <= 0) {
43 return 0;
44 }
45
46 if (rounding_value <= 0) {
47 return 0;
48 }
49
50 return (input_value / rounding_value) * rounding_value;
51 }
52
53 // Returns the minimum integer value which is a multiple of rounding_value,
54 // and greater than or equal to input_value.
55 //
56 // input_value must be greater than or equal to zero, or else returns 0.
57 // rounding_value must be greater than or equal to zero, or else returns 0.
58 template <typename IntType>
RoundUpTo(IntType input_value,IntType rounding_value)59 static IntType RoundUpTo(IntType input_value, IntType rounding_value) {
60 static_assert(std::numeric_limits<IntType>::is_integer,
61 "RoundUpTo() operation type is not integer");
62
63 if (input_value <= 0) {
64 return 0;
65 }
66
67 if (rounding_value <= 0) {
68 return 0;
69 }
70
71 const IntType remainder = input_value % rounding_value;
72 return (remainder == 0) ? input_value
73 : (input_value - remainder + rounding_value);
74 }
75
76 } // namespace math_util
77
78 } // namespace lib
79 } // namespace icing
80
81 #endif // ICING_UTIL_MATH_UTIL_H_
82