• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #ifndef GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_
31 #define GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_
32 
33 #include <cmath>
34 #include <float.h>
35 #include <limits>
36 
37 #include <google/protobuf/stubs/common.h>
38 #include <google/protobuf/stubs/logging.h>
39 
40 namespace google {
41 namespace protobuf {
42 namespace internal {
43 
44 // Like std::make_unsigned_t except floating point types map to themselves.
45 template <typename T>
46 using MakeUnsignedT =
47     typename std::conditional<std::is_integral<T>::value, std::make_unsigned<T>,
48                               std::common_type<T>>::type::type;
49 
50 // Like std::isnan() except a template function that is defined for all numeric
51 // types.
52 template <typename T,
53           typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
IsNan(T val)54 bool IsNan(T val) {
55   return false;
56 }
57 
58 template <typename T, typename std::enable_if<std::is_floating_point<T>::value,
59                                               int>::type = 0>
IsNan(T val)60 bool IsNan(T val) {
61   return std::isnan(val);
62 }
63 
64 template<typename T>
AlmostEquals(T a,T b)65 bool AlmostEquals(T a, T b) {
66   return a == b;
67 }
68 template<>
AlmostEquals(float a,float b)69 inline bool AlmostEquals(float a, float b) {
70   return fabs(a - b) < 32 * FLT_EPSILON;
71 }
72 
73 template<>
AlmostEquals(double a,double b)74 inline bool AlmostEquals(double a, double b) {
75   return fabs(a - b) < 32 * DBL_EPSILON;
76 }
77 
78 }  // namespace internal
79 
80 class MathUtil {
81  public:
82   template <typename T>
Sign(T value)83   static T Sign(T value) {
84     if (value == T(0) || internal::IsNan(value)) {
85       return value;
86     }
87     return value > T(0) ? 1 : -1;
88   }
89 
90   template <typename T>
AlmostEquals(T a,T b)91   static bool AlmostEquals(T a, T b) {
92     return internal::AlmostEquals(a, b);
93   }
94 
95   // Largest of two values.
96   // Works correctly for special floating point values.
97   // Note: 0.0 and -0.0 are not differentiated by Max (Max(0.0, -0.0) is -0.0),
98   // which should be OK because, although they (can) have different
99   // bit representation, they are observably the same when examined
100   // with arithmetic and (in)equality operators.
101   template <typename T>
Max(const T x,const T y)102   static T Max(const T x, const T y) {
103     return internal::IsNan(x) || x > y ? x : y;
104   }
105 
106   // Absolute value of x
107   // Works correctly for unsigned types and
108   // for special floating point values.
109   // Note: 0.0 and -0.0 are not differentiated by Abs (Abs(0.0) is -0.0),
110   // which should be OK: see the comment for Max above.
111   template<typename T>
Abs(const T x)112   static T Abs(const T x) {
113     return x > T(0) ? x : -x;
114   }
115 
116   // Absolute value of the difference between two numbers.
117   // Works correctly for signed types and special floating point values.
118   template <typename T>
AbsDiff(const T x,const T y)119   static typename internal::MakeUnsignedT<T> AbsDiff(const T x, const T y) {
120     // Carries out arithmetic as unsigned to avoid overflow.
121     typedef typename internal::MakeUnsignedT<T> R;
122     return x > y ? R(x) - R(y) : R(y) - R(x);
123   }
124 
125   // If two (usually floating point) numbers are within a certain
126   // fraction of their magnitude or within a certain absolute margin of error.
127   // This is the same as the following but faster:
128   //   WithinFraction(x, y, fraction)  ||  WithinMargin(x, y, margin)
129   // E.g. WithinFraction(0.0, 1e-10, 1e-5) is false but
130   //      WithinFractionOrMargin(0.0, 1e-10, 1e-5, 1e-5) is true.
131   template<typename T>
132   static bool WithinFractionOrMargin(const T x, const T y,
133                                      const T fraction, const T margin);
134 };
135 
136 template<typename T>
WithinFractionOrMargin(const T x,const T y,const T fraction,const T margin)137 bool MathUtil::WithinFractionOrMargin(const T x, const T y,
138                                       const T fraction, const T margin) {
139   // Not just "0 <= fraction" to fool the compiler for unsigned types.
140   GOOGLE_DCHECK((T(0) < fraction || T(0) == fraction) &&
141          fraction < T(1) &&
142          margin >= T(0));
143 
144   // Template specialization will convert the if() condition to a constant,
145   // which will cause the compiler to generate code for either the "if" part
146   // or the "then" part.  In this way we avoid a compiler warning
147   // about a potential integer overflow in crosstool v12 (gcc 4.3.1).
148   if (std::numeric_limits<T>::is_integer) {
149     return x == y;
150   } else {
151     if (!std::isfinite(x) || !std::isfinite(y)) {
152       return false;
153     }
154     T relative_margin = static_cast<T>(fraction * Max(Abs(x), Abs(y)));
155     return AbsDiff(x, y) <= Max(margin, relative_margin);
156   }
157 }
158 
159 }  // namespace protobuf
160 }  // namespace google
161 
162 #endif  // GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_
163