Remove mathutil stub.

This reduces the implementation to our much narrower current use-cases, hardcoded directly where we need it.  It also unifies google3 and OSS behavior, which may have deviated over time.

PiperOrigin-RevId: 502696374
pull/11128/head
Mike Kruskal 2 years ago committed by Copybara-Service
parent 5a8abe1c20
commit 021435611f
  1. 2
      src/google/protobuf/stubs/BUILD.bazel
  2. 163
      src/google/protobuf/stubs/mathutil.h
  3. 42
      src/google/protobuf/util/field_comparator.cc
  4. 7
      src/google/protobuf/util/field_comparator_test.cc

@ -18,7 +18,6 @@ cc_library(
"callback.h",
"common.h",
"logging.h",
"mathutil.h",
"platform_macros.h",
"port.h",
"status_macros.h",
@ -45,7 +44,6 @@ cc_library(
"callback.h",
"common.h",
"logging.h",
"mathutil.h",
"platform_macros.h",
"port.h",
"status_macros.h",

@ -1,163 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_
#define GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_
#include <float.h>
#include <cmath>
#include <limits>
#include "google/protobuf/stubs/common.h"
#include "google/protobuf/stubs/logging.h"
namespace google {
namespace protobuf {
namespace internal {
// Like std::make_unsigned_t except floating point types map to themselves.
template <typename T>
using MakeUnsignedT =
typename std::conditional<std::is_integral<T>::value, std::make_unsigned<T>,
std::common_type<T>>::type::type;
// Like std::isnan() except a template function that is defined for all numeric
// types.
template <typename T,
typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
bool IsNan(T /*val*/) {
return false;
}
template <typename T, typename std::enable_if<std::is_floating_point<T>::value,
int>::type = 0>
bool IsNan(T val) {
return std::isnan(val);
}
template<typename T>
bool AlmostEquals(T a, T b) {
return a == b;
}
template<>
inline bool AlmostEquals(float a, float b) {
return fabs(a - b) < 32 * FLT_EPSILON;
}
template<>
inline bool AlmostEquals(double a, double b) {
return fabs(a - b) < 32 * DBL_EPSILON;
}
} // namespace internal
class MathUtil {
public:
template <typename T>
static T Sign(T value) {
if (value == T(0) || internal::IsNan(value)) {
return value;
}
return value > T(0) ? 1 : -1;
}
template <typename T>
static bool AlmostEquals(T a, T b) {
return internal::AlmostEquals(a, b);
}
// Largest of two values.
// Works correctly for special floating point values.
// Note: 0.0 and -0.0 are not differentiated by Max (Max(0.0, -0.0) is -0.0),
// which should be OK because, although they (can) have different
// bit representation, they are observably the same when examined
// with arithmetic and (in)equality operators.
template <typename T>
static T Max(const T x, const T y) {
return internal::IsNan(x) || x > y ? x : y;
}
// Absolute value of x
// Works correctly for unsigned types and
// for special floating point values.
// Note: 0.0 and -0.0 are not differentiated by Abs (Abs(0.0) is -0.0),
// which should be OK: see the comment for Max above.
template<typename T>
static T Abs(const T x) {
return x > T(0) ? x : -x;
}
// Absolute value of the difference between two numbers.
// Works correctly for signed types and special floating point values.
template <typename T>
static typename internal::MakeUnsignedT<T> AbsDiff(const T x, const T y) {
// Carries out arithmetic as unsigned to avoid overflow.
typedef typename internal::MakeUnsignedT<T> R;
return x > y ? R(x) - R(y) : R(y) - R(x);
}
// If two (usually floating point) numbers are within a certain
// fraction of their magnitude or within a certain absolute margin of error.
// This is the same as the following but faster:
// WithinFraction(x, y, fraction) || WithinMargin(x, y, margin)
// E.g. WithinFraction(0.0, 1e-10, 1e-5) is false but
// WithinFractionOrMargin(0.0, 1e-10, 1e-5, 1e-5) is true.
template<typename T>
static bool WithinFractionOrMargin(const T x, const T y,
const T fraction, const T margin);
};
template<typename T>
bool MathUtil::WithinFractionOrMargin(const T x, const T y,
const T fraction, const T margin) {
// Not just "0 <= fraction" to fool the compiler for unsigned types.
GOOGLE_DCHECK((T(0) < fraction || T(0) == fraction) &&
fraction < T(1) &&
margin >= T(0));
// Template specialization will convert the if() condition to a constant,
// which will cause the compiler to generate code for either the "if" part
// or the "then" part. In this way we avoid a compiler warning
// about a potential integer overflow in crosstool v12 (gcc 4.3.1).
if (std::numeric_limits<T>::is_integer) {
return x == y;
} else {
if (!std::isfinite(x) || !std::isfinite(y)) {
return false;
}
T relative_margin = static_cast<T>(fraction * Max(Abs(x), Abs(y)));
return AbsDiff(x, y) <= Max(margin, relative_margin);
}
}
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_

@ -32,6 +32,9 @@
#include "google/protobuf/util/field_comparator.h"
#include <algorithm>
#include <cfloat>
#include <cmath>
#include <limits>
#include <string>
@ -40,11 +43,35 @@
#include "google/protobuf/stubs/logging.h"
#include "google/protobuf/stubs/logging.h"
#include "google/protobuf/util/message_differencer.h"
#include "google/protobuf/stubs/mathutil.h"
namespace google {
namespace protobuf {
namespace util {
namespace {
template <typename T>
struct Epsilon {};
template <>
struct Epsilon<float> {
constexpr static auto value = 32 * FLT_EPSILON;
};
template <>
struct Epsilon<double> {
constexpr static auto value = 32 * DBL_EPSILON;
};
template <typename T>
bool WithinFractionOrMargin(const T x, const T y, const T fraction,
const T margin) {
GOOGLE_ABSL_DCHECK(fraction >= T(0) && fraction < T(1) && margin >= T(0));
if (!std::isfinite(x) || !std::isfinite(y)) {
return false;
}
const T relative_margin = fraction * std::max(std::fabs(x), std::fabs(y));
return std::fabs(x - y) <= std::max(margin, relative_margin);
}
} // namespace
FieldComparator::FieldComparator() {}
FieldComparator::~FieldComparator() {}
@ -196,11 +223,16 @@ bool SimpleFieldComparator::CompareDoubleOrFloat(const FieldDescriptor& field,
// Use user-provided fraction and margin. Since they are stored as
// doubles, we explicitly cast them to types of values provided. This
// is very likely to fail if provided values are not numeric.
return MathUtil::WithinFractionOrMargin(
value_1, value_2, static_cast<T>(tolerance->fraction),
static_cast<T>(tolerance->margin));
return WithinFractionOrMargin(value_1, value_2,
static_cast<T>(tolerance->fraction),
static_cast<T>(tolerance->margin));
} else {
return MathUtil::AlmostEquals(value_1, value_2);
if (std::fabs(value_1) <= Epsilon<T>::value &&
std::fabs(value_2) <= Epsilon<T>::value) {
return true;
}
return WithinFractionOrMargin(value_1, value_2, Epsilon<T>::value,
Epsilon<T>::value);
}
}
}

@ -37,7 +37,6 @@
#include "google/protobuf/descriptor.h"
#include <gtest/gtest.h>
#include "google/protobuf/unittest.pb.h"
#include "google/protobuf/stubs/mathutil.h"
namespace google {
namespace protobuf {
@ -225,10 +224,8 @@ TEST_F(DefaultFieldComparatorTest, FloatingPointComparisonApproximate) {
// results first to check if that's where the failure was introduced.
ASSERT_NE(message_1_.optional_float(), message_2_.optional_float());
ASSERT_NE(message_1_.optional_double(), message_2_.optional_double());
ASSERT_TRUE(MathUtil::AlmostEquals(message_1_.optional_float(),
message_2_.optional_float()));
ASSERT_TRUE(MathUtil::AlmostEquals(message_1_.optional_double(),
message_2_.optional_double()));
ASSERT_FLOAT_EQ(message_1_.optional_float(), message_2_.optional_float());
ASSERT_DOUBLE_EQ(message_1_.optional_double(), message_2_.optional_double());
// DefaultFieldComparator's default float comparison mode is EXACT.
ASSERT_EQ(DefaultFieldComparator::EXACT, comparator_.float_comparison());

Loading…
Cancel
Save