field_comparator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. // Defines classes for field comparison.
  31. #ifndef GOOGLE_PROTOBUF_UTIL_FIELD_COMPARATOR_H__
  32. #define GOOGLE_PROTOBUF_UTIL_FIELD_COMPARATOR_H__
  33. #include <cstdint>
  34. #include <map>
  35. #include <string>
  36. #include <vector>
  37. #include <google/protobuf/stubs/common.h>
  38. #include <google/protobuf/port_def.inc>
  39. namespace google {
  40. namespace protobuf {
  41. class Message;
  42. class EnumValueDescriptor;
  43. class FieldDescriptor;
  44. namespace util {
  45. class FieldContext;
  46. class MessageDifferencer;
  47. // Base class specifying the interface for comparing protocol buffer fields.
  48. // Regular users should consider using or subclassing DefaultFieldComparator
  49. // rather than this interface.
  50. // Currently, this does not support comparing unknown fields.
  51. class PROTOBUF_EXPORT FieldComparator {
  52. public:
  53. FieldComparator();
  54. virtual ~FieldComparator();
  55. enum ComparisonResult {
  56. SAME, // Compared fields are equal. In case of comparing submessages,
  57. // user should not recursively compare their contents.
  58. DIFFERENT, // Compared fields are different. In case of comparing
  59. // submessages, user should not recursively compare their
  60. // contents.
  61. RECURSE, // Compared submessages need to be compared recursively.
  62. // FieldComparator does not specify the semantics of recursive
  63. // comparison. This value should not be returned for simple
  64. // values.
  65. };
  66. // Compares the values of a field in two protocol buffer messages.
  67. // Returns SAME or DIFFERENT for simple values, and SAME, DIFFERENT or RECURSE
  68. // for submessages. Returning RECURSE for fields not being submessages is
  69. // illegal.
  70. // In case the given FieldDescriptor points to a repeated field, the indices
  71. // need to be valid. Otherwise they should be ignored.
  72. //
  73. // FieldContext contains information about the specific instances of the
  74. // fields being compared, versus FieldDescriptor which only contains general
  75. // type information about the fields.
  76. virtual ComparisonResult Compare(const Message& message_1,
  77. const Message& message_2,
  78. const FieldDescriptor* field, int index_1,
  79. int index_2,
  80. const util::FieldContext* field_context) = 0;
  81. private:
  82. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldComparator);
  83. };
  84. // Basic implementation of FieldComparator. Supports three modes of floating
  85. // point value comparison: exact, approximate using MathUtil::AlmostEqual
  86. // method, and arbitrarily precise using MathUtil::WithinFractionOrMargin.
  87. class PROTOBUF_EXPORT SimpleFieldComparator : public FieldComparator {
  88. public:
  89. enum FloatComparison {
  90. EXACT, // Floats and doubles are compared exactly.
  91. APPROXIMATE, // Floats and doubles are compared using the
  92. // MathUtil::AlmostEqual method or
  93. // MathUtil::WithinFractionOrMargin method.
  94. // TODO(ksroka): Introduce third value to differentiate uses of AlmostEqual
  95. // and WithinFractionOrMargin.
  96. };
  97. // Creates new comparator with float comparison set to EXACT.
  98. SimpleFieldComparator();
  99. ~SimpleFieldComparator() override;
  100. void set_float_comparison(FloatComparison float_comparison) {
  101. float_comparison_ = float_comparison;
  102. }
  103. FloatComparison float_comparison() const { return float_comparison_; }
  104. // Set whether the FieldComparator shall treat floats or doubles that are both
  105. // NaN as equal (treat_nan_as_equal = true) or as different
  106. // (treat_nan_as_equal = false). Default is treating NaNs always as different.
  107. void set_treat_nan_as_equal(bool treat_nan_as_equal) {
  108. treat_nan_as_equal_ = treat_nan_as_equal;
  109. }
  110. bool treat_nan_as_equal() const { return treat_nan_as_equal_; }
  111. // Sets the fraction and margin for the float comparison of a given field.
  112. // Uses MathUtil::WithinFractionOrMargin to compare the values.
  113. //
  114. // REQUIRES: field->cpp_type == FieldDescriptor::CPPTYPE_DOUBLE or
  115. // field->cpp_type == FieldDescriptor::CPPTYPE_FLOAT
  116. // REQUIRES: float_comparison_ == APPROXIMATE
  117. void SetFractionAndMargin(const FieldDescriptor* field, double fraction,
  118. double margin);
  119. // Sets the fraction and margin for the float comparison of all float and
  120. // double fields, unless a field has been given a specific setting via
  121. // SetFractionAndMargin() above.
  122. // Uses MathUtil::WithinFractionOrMargin to compare the values.
  123. //
  124. // REQUIRES: float_comparison_ == APPROXIMATE
  125. void SetDefaultFractionAndMargin(double fraction, double margin);
  126. protected:
  127. // Returns the comparison result for the given field in two messages.
  128. //
  129. // This function is called directly by DefaultFieldComparator::Compare.
  130. // Subclasses can call this function to compare fields they do not need to
  131. // handle specially.
  132. ComparisonResult SimpleCompare(const Message& message_1,
  133. const Message& message_2,
  134. const FieldDescriptor* field, int index_1,
  135. int index_2,
  136. const util::FieldContext* field_context);
  137. // Compare using the provided message_differencer. For example, a subclass can
  138. // use this method to compare some field in a certain way using the same
  139. // message_differencer instance and the field context.
  140. bool CompareWithDifferencer(MessageDifferencer* differencer,
  141. const Message& message1, const Message& message2,
  142. const util::FieldContext* field_context);
  143. // Returns FieldComparator::SAME if boolean_result is true and
  144. // FieldComparator::DIFFERENT otherwise.
  145. ComparisonResult ResultFromBoolean(bool boolean_result) const;
  146. private:
  147. // Defines the tolerance for floating point comparison (fraction and margin).
  148. struct Tolerance {
  149. double fraction;
  150. double margin;
  151. Tolerance() : fraction(0.0), margin(0.0) {}
  152. Tolerance(double f, double m) : fraction(f), margin(m) {}
  153. };
  154. // Defines the map to store the tolerances for floating point comparison.
  155. typedef std::map<const FieldDescriptor*, Tolerance> ToleranceMap;
  156. friend class MessageDifferencer;
  157. // The following methods get executed when CompareFields is called for the
  158. // basic types (instead of submessages). They return true on success. One
  159. // can use ResultFromBoolean() to convert that boolean to a ComparisonResult
  160. // value.
  161. bool CompareBool(const FieldDescriptor& /* unused */, bool value_1,
  162. bool value_2) {
  163. return value_1 == value_2;
  164. }
  165. // Uses CompareDoubleOrFloat, a helper function used by both CompareDouble and
  166. // CompareFloat.
  167. bool CompareDouble(const FieldDescriptor& field, double value_1,
  168. double value_2);
  169. bool CompareEnum(const FieldDescriptor& field,
  170. const EnumValueDescriptor* value_1,
  171. const EnumValueDescriptor* value_2);
  172. // Uses CompareDoubleOrFloat, a helper function used by both CompareDouble and
  173. // CompareFloat.
  174. bool CompareFloat(const FieldDescriptor& field, float value_1, float value_2);
  175. bool CompareInt32(const FieldDescriptor& /* unused */, int32_t value_1,
  176. int32_t value_2) {
  177. return value_1 == value_2;
  178. }
  179. bool CompareInt64(const FieldDescriptor& /* unused */, int64_t value_1,
  180. int64_t value_2) {
  181. return value_1 == value_2;
  182. }
  183. bool CompareString(const FieldDescriptor& /* unused */,
  184. const std::string& value_1, const std::string& value_2) {
  185. return value_1 == value_2;
  186. }
  187. bool CompareUInt32(const FieldDescriptor& /* unused */, uint32_t value_1,
  188. uint32_t value_2) {
  189. return value_1 == value_2;
  190. }
  191. bool CompareUInt64(const FieldDescriptor& /* unused */, uint64_t value_1,
  192. uint64_t value_2) {
  193. return value_1 == value_2;
  194. }
  195. // This function is used by CompareDouble and CompareFloat to avoid code
  196. // duplication. There are no checks done against types of the values passed,
  197. // but it's likely to fail if passed non-numeric arguments.
  198. template <typename T>
  199. bool CompareDoubleOrFloat(const FieldDescriptor& field, T value_1, T value_2);
  200. FloatComparison float_comparison_;
  201. // If true, floats and doubles that are both NaN are considered to be
  202. // equal. Otherwise, two floats or doubles that are NaN are considered to be
  203. // different.
  204. bool treat_nan_as_equal_;
  205. // True iff default_tolerance_ has been explicitly set.
  206. //
  207. // If false, then the default tolerance for floats and doubles is that which
  208. // is used by MathUtil::AlmostEquals().
  209. bool has_default_tolerance_;
  210. // Default float/double tolerance. Only meaningful if
  211. // has_default_tolerance_ == true.
  212. Tolerance default_tolerance_;
  213. // Field-specific float/double tolerances, which override any default for
  214. // those particular fields.
  215. ToleranceMap map_tolerance_;
  216. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SimpleFieldComparator);
  217. };
  218. // Default field comparison: use the basic implementation of FieldComparator.
  219. #ifdef PROTOBUF_FUTURE_BREAKING_CHANGES
  220. class PROTOBUF_EXPORT DefaultFieldComparator final
  221. : public SimpleFieldComparator
  222. #else // PROTOBUF_FUTURE_BREAKING_CHANGES
  223. class PROTOBUF_EXPORT DefaultFieldComparator : public SimpleFieldComparator
  224. #endif // PROTOBUF_FUTURE_BREAKING_CHANGES
  225. {
  226. public:
  227. ComparisonResult Compare(const Message& message_1, const Message& message_2,
  228. const FieldDescriptor* field, int index_1,
  229. int index_2,
  230. const util::FieldContext* field_context) override {
  231. return SimpleCompare(message_1, message_2, field, index_1, index_2,
  232. field_context);
  233. }
  234. };
  235. } // namespace util
  236. } // namespace protobuf
  237. } // namespace google
  238. #include <google/protobuf/port_undef.inc>
  239. #endif // GOOGLE_PROTOBUF_UTIL_FIELD_COMPARATOR_H__