诸暨麻将添加redis
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

921 line
45 KiB

  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. // Author: jschorr@google.com (Joseph Schorr)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. //
  34. // This file defines static methods and classes for comparing Protocol
  35. // Messages.
  36. //
  37. // Aug. 2008: Added Unknown Fields Comparison for messages.
  38. // Aug. 2009: Added different options to compare repeated fields.
  39. // Apr. 2010: Moved field comparison to FieldComparator.
  40. #ifndef GOOGLE_PROTOBUF_UTIL_MESSAGE_DIFFERENCER_H__
  41. #define GOOGLE_PROTOBUF_UTIL_MESSAGE_DIFFERENCER_H__
  42. #include <functional>
  43. #include <map>
  44. #include <set>
  45. #include <string>
  46. #include <vector>
  47. #include <google/protobuf/descriptor.h> // FieldDescriptor
  48. #include <google/protobuf/message.h> // Message
  49. #include <google/protobuf/unknown_field_set.h>
  50. #include <google/protobuf/util/field_comparator.h>
  51. // Always include as last one, otherwise it can break compilation
  52. #include <google/protobuf/port_def.inc>
  53. namespace google {
  54. namespace protobuf {
  55. class DynamicMessageFactory;
  56. class FieldDescriptor;
  57. namespace io {
  58. class ZeroCopyOutputStream;
  59. class Printer;
  60. } // namespace io
  61. namespace util {
  62. class DefaultFieldComparator;
  63. class FieldContext; // declared below MessageDifferencer
  64. // Defines a collection of field descriptors.
  65. // In case of internal google codebase we are using absl::FixedArray instead
  66. // of vector. It significantly speeds up proto comparison (by ~30%) by
  67. // reducing the number of malloc/free operations
  68. typedef std::vector<const FieldDescriptor*> FieldDescriptorArray;
  69. // A basic differencer that can be used to determine
  70. // the differences between two specified Protocol Messages. If any differences
  71. // are found, the Compare method will return false, and any differencer reporter
  72. // specified via ReportDifferencesTo will have its reporting methods called (see
  73. // below for implementation of the report). Based off of the original
  74. // ProtocolDifferencer implementation in //net/proto/protocol-differencer.h
  75. // (Thanks Todd!).
  76. //
  77. // MessageDifferencer REQUIRES that compared messages be the same type, defined
  78. // as messages that share the same descriptor. If not, the behavior of this
  79. // class is undefined.
  80. //
  81. // People disagree on what MessageDifferencer should do when asked to compare
  82. // messages with different descriptors. Some people think it should always
  83. // return false. Others expect it to try to look for similar fields and
  84. // compare them anyway -- especially if the descriptors happen to be identical.
  85. // If we chose either of these behaviors, some set of people would find it
  86. // surprising, and could end up writing code expecting the other behavior
  87. // without realizing their error. Therefore, we forbid that usage.
  88. //
  89. // This class is implemented based on the proto2 reflection. The performance
  90. // should be good enough for normal usages. However, for places where the
  91. // performance is extremely sensitive, there are several alternatives:
  92. // - Comparing serialized string
  93. // Downside: false negatives (there are messages that are the same but their
  94. // serialized strings are different).
  95. // - Equals code generator by compiler plugin (net/proto2/contrib/equals_plugin)
  96. // Downside: more generated code; maintenance overhead for the additional rule
  97. // (must be in sync with the original proto_library).
  98. //
  99. // Note on handling of google.protobuf.Any: MessageDifferencer automatically
  100. // unpacks Any::value into a Message and compares its individual fields.
  101. // Messages encoded in a repeated Any cannot be compared using TreatAsMap.
  102. //
  103. // Note on thread-safety: MessageDifferencer is *not* thread-safe. You need to
  104. // guard it with a lock to use the same MessageDifferencer instance from
  105. // multiple threads. Note that it's fine to call static comparison methods
  106. // (like MessageDifferencer::Equals) concurrently, but it's not recommended for
  107. // performance critical code as it leads to extra allocations.
  108. class PROTOBUF_EXPORT MessageDifferencer {
  109. public:
  110. // Determines whether the supplied messages are equal. Equality is defined as
  111. // all fields within the two messages being set to the same value. Primitive
  112. // fields and strings are compared by value while embedded messages/groups
  113. // are compared as if via a recursive call. Use Compare() with IgnoreField()
  114. // if some fields should be ignored in the comparison. Use Compare() with
  115. // TreatAsSet() if there are repeated fields where ordering does not matter.
  116. //
  117. // This method REQUIRES that the two messages have the same
  118. // Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
  119. static bool Equals(const Message& message1, const Message& message2);
  120. // Determines whether the supplied messages are equivalent. Equivalency is
  121. // defined as all fields within the two messages having the same value. This
  122. // differs from the Equals method above in that fields with default values
  123. // are considered set to said value automatically. For details on how default
  124. // values are defined for each field type, see:
  125. // https://developers.google.com/protocol-buffers/docs/proto?csw=1#optional.
  126. // Also, Equivalent() ignores unknown fields. Use IgnoreField() and Compare()
  127. // if some fields should be ignored in the comparison.
  128. //
  129. // This method REQUIRES that the two messages have the same
  130. // Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
  131. static bool Equivalent(const Message& message1, const Message& message2);
  132. // Determines whether the supplied messages are approximately equal.
  133. // Approximate equality is defined as all fields within the two messages
  134. // being approximately equal. Primitive (non-float) fields and strings are
  135. // compared by value, floats are compared using MathUtil::AlmostEquals() and
  136. // embedded messages/groups are compared as if via a recursive call. Use
  137. // IgnoreField() and Compare() if some fields should be ignored in the
  138. // comparison.
  139. //
  140. // This method REQUIRES that the two messages have the same
  141. // Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
  142. static bool ApproximatelyEquals(const Message& message1,
  143. const Message& message2);
  144. // Determines whether the supplied messages are approximately equivalent.
  145. // Approximate equivalency is defined as all fields within the two messages
  146. // being approximately equivalent. As in
  147. // MessageDifferencer::ApproximatelyEquals, primitive (non-float) fields and
  148. // strings are compared by value, floats are compared using
  149. // MathUtil::AlmostEquals() and embedded messages/groups are compared as if
  150. // via a recursive call. However, fields with default values are considered
  151. // set to said value, as per MessageDiffencer::Equivalent. Use IgnoreField()
  152. // and Compare() if some fields should be ignored in the comparison.
  153. //
  154. // This method REQUIRES that the two messages have the same
  155. // Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
  156. static bool ApproximatelyEquivalent(const Message& message1,
  157. const Message& message2);
  158. // Identifies an individual field in a message instance. Used for field_path,
  159. // below.
  160. struct SpecificField {
  161. // For known fields, "field" is filled in and "unknown_field_number" is -1.
  162. // For unknown fields, "field" is NULL, "unknown_field_number" is the field
  163. // number, and "unknown_field_type" is its type.
  164. const FieldDescriptor* field;
  165. int unknown_field_number;
  166. UnknownField::Type unknown_field_type;
  167. // If this a repeated field, "index" is the index within it. For unknown
  168. // fields, this is the index of the field among all unknown fields of the
  169. // same field number and type.
  170. int index;
  171. // If "field" is a repeated field which is being treated as a map or
  172. // a set (see TreatAsMap() and TreatAsSet(), below), new_index indicates
  173. // the index the position to which the element has moved. If the element
  174. // has not moved, "new_index" will have the same value as "index".
  175. int new_index;
  176. // For unknown fields, these are the pointers to the UnknownFieldSet
  177. // containing the unknown fields. In certain cases (e.g. proto1's
  178. // MessageSet, or nested groups of unknown fields), these may differ from
  179. // the messages' internal UnknownFieldSets.
  180. const UnknownFieldSet* unknown_field_set1;
  181. const UnknownFieldSet* unknown_field_set2;
  182. // For unknown fields, these are the index of the field within the
  183. // UnknownFieldSets. One or the other will be -1 when
  184. // reporting an addition or deletion.
  185. int unknown_field_index1;
  186. int unknown_field_index2;
  187. SpecificField()
  188. : field(NULL),
  189. unknown_field_number(-1),
  190. index(-1),
  191. new_index(-1),
  192. unknown_field_set1(NULL),
  193. unknown_field_set2(NULL),
  194. unknown_field_index1(-1),
  195. unknown_field_index2(-1) {}
  196. };
  197. // Abstract base class from which all MessageDifferencer
  198. // reporters derive. The five Report* methods below will be called when
  199. // a field has been added, deleted, modified, moved, or matched. The third
  200. // argument is a vector of FieldDescriptor pointers which describes the chain
  201. // of fields that was taken to find the current field. For example, for a
  202. // field found in an embedded message, the vector will contain two
  203. // FieldDescriptors. The first will be the field of the embedded message
  204. // itself and the second will be the actual field in the embedded message
  205. // that was added/deleted/modified.
  206. class PROTOBUF_EXPORT Reporter {
  207. public:
  208. Reporter();
  209. virtual ~Reporter();
  210. // Reports that a field has been added into Message2.
  211. virtual void ReportAdded(const Message& message1, const Message& message2,
  212. const std::vector<SpecificField>& field_path) = 0;
  213. // Reports that a field has been deleted from Message1.
  214. virtual void ReportDeleted(
  215. const Message& message1, const Message& message2,
  216. const std::vector<SpecificField>& field_path) = 0;
  217. // Reports that the value of a field has been modified.
  218. virtual void ReportModified(
  219. const Message& message1, const Message& message2,
  220. const std::vector<SpecificField>& field_path) = 0;
  221. // Reports that a repeated field has been moved to another location. This
  222. // only applies when using TreatAsSet or TreatAsMap() -- see below. Also
  223. // note that for any given field, ReportModified and ReportMoved are
  224. // mutually exclusive. If a field has been both moved and modified, then
  225. // only ReportModified will be called.
  226. virtual void ReportMoved(
  227. const Message& /* message1 */, const Message& /* message2 */,
  228. const std::vector<SpecificField>& /* field_path */) {}
  229. // Reports that two fields match. Useful for doing side-by-side diffs.
  230. // This function is mutually exclusive with ReportModified and ReportMoved.
  231. // Note that you must call set_report_matches(true) before calling Compare
  232. // to make use of this function.
  233. virtual void ReportMatched(
  234. const Message& /* message1 */, const Message& /* message2 */,
  235. const std::vector<SpecificField>& /* field_path */) {}
  236. // Reports that two fields would have been compared, but the
  237. // comparison has been skipped because the field was marked as
  238. // 'ignored' using IgnoreField(). This function is mutually
  239. // exclusive with all the other Report() functions.
  240. //
  241. // The contract of ReportIgnored is slightly different than the
  242. // other Report() functions, in that |field_path.back().index| is
  243. // always equal to -1, even if the last field is repeated. This is
  244. // because while the other Report() functions indicate where in a
  245. // repeated field the action (Addition, Deletion, etc...)
  246. // happened, when a repeated field is 'ignored', the differencer
  247. // simply calls ReportIgnored on the repeated field as a whole and
  248. // moves on without looking at its individual elements.
  249. //
  250. // Furthermore, ReportIgnored() does not indicate whether the
  251. // fields were in fact equal or not, as Compare() does not inspect
  252. // these fields at all. It is up to the Reporter to decide whether
  253. // the fields are equal or not (perhaps with a second call to
  254. // Compare()), if it cares.
  255. virtual void ReportIgnored(
  256. const Message& /* message1 */, const Message& /* message2 */,
  257. const std::vector<SpecificField>& /* field_path */) {}
  258. // Report that an unknown field is ignored. (see comment above).
  259. // Note this is a different function since the last SpecificField in field
  260. // path has a null field. This could break existing Reporter.
  261. virtual void ReportUnknownFieldIgnored(
  262. const Message& /* message1 */, const Message& /* message2 */,
  263. const std::vector<SpecificField>& /* field_path */) {}
  264. private:
  265. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reporter);
  266. };
  267. // MapKeyComparator is used to determine if two elements have the same key
  268. // when comparing elements of a repeated field as a map.
  269. class PROTOBUF_EXPORT MapKeyComparator {
  270. public:
  271. MapKeyComparator();
  272. virtual ~MapKeyComparator();
  273. virtual bool IsMatch(
  274. const Message& /* message1 */, const Message& /* message2 */,
  275. const std::vector<SpecificField>& /* parent_fields */) const {
  276. GOOGLE_CHECK(false) << "IsMatch() is not implemented.";
  277. return false;
  278. }
  279. private:
  280. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapKeyComparator);
  281. };
  282. // Abstract base class from which all IgnoreCriteria derive.
  283. // By adding IgnoreCriteria more complex ignore logic can be implemented.
  284. // IgnoreCriteria are registed with AddIgnoreCriteria. For each compared
  285. // field IsIgnored is called on each added IgnoreCriteria until one returns
  286. // true or all return false.
  287. // IsIgnored is called for fields where at least one side has a value.
  288. class PROTOBUF_EXPORT IgnoreCriteria {
  289. public:
  290. IgnoreCriteria();
  291. virtual ~IgnoreCriteria();
  292. // Returns true if the field should be ignored.
  293. virtual bool IsIgnored(
  294. const Message& /* message1 */, const Message& /* message2 */,
  295. const FieldDescriptor* /* field */,
  296. const std::vector<SpecificField>& /* parent_fields */) = 0;
  297. // Returns true if the unknown field should be ignored.
  298. // Note: This will be called for unknown fields as well in which case
  299. // field.field will be null.
  300. virtual bool IsUnknownFieldIgnored(
  301. const Message& /* message1 */, const Message& /* message2 */,
  302. const SpecificField& /* field */,
  303. const std::vector<SpecificField>& /* parent_fields */) {
  304. return false;
  305. }
  306. };
  307. // To add a Reporter, construct default here, then use ReportDifferencesTo or
  308. // ReportDifferencesToString.
  309. explicit MessageDifferencer();
  310. ~MessageDifferencer();
  311. enum MessageFieldComparison {
  312. EQUAL, // Fields must be present in both messages
  313. // for the messages to be considered the same.
  314. EQUIVALENT, // Fields with default values are considered set
  315. // for comparison purposes even if not explicitly
  316. // set in the messages themselves. Unknown fields
  317. // are ignored.
  318. };
  319. enum Scope {
  320. FULL, // All fields of both messages are considered in the comparison.
  321. PARTIAL // Only fields present in the first message are considered; fields
  322. // set only in the second message will be skipped during
  323. // comparison.
  324. };
  325. // DEPRECATED. Use FieldComparator::FloatComparison instead.
  326. enum FloatComparison {
  327. EXACT, // Floats and doubles are compared exactly.
  328. APPROXIMATE // Floats and doubles are compared using the
  329. // MathUtil::AlmostEquals method.
  330. };
  331. enum RepeatedFieldComparison {
  332. AS_LIST, // Repeated fields are compared in order. Differing values at
  333. // the same index are reported using ReportModified(). If the
  334. // repeated fields have different numbers of elements, the
  335. // unpaired elements are reported using ReportAdded() or
  336. // ReportDeleted().
  337. AS_SET, // Treat all the repeated fields as sets.
  338. // See TreatAsSet(), as below.
  339. AS_SMART_LIST, // Similar to AS_SET, but preserve the order and find the
  340. // longest matching sequence from the first matching
  341. // element. To use an optimal solution, call
  342. // SetMatchIndicesForSmartListCallback() to pass it in.
  343. AS_SMART_SET, // Similar to AS_SET, but match elements with fewest diffs.
  344. };
  345. // The elements of the given repeated field will be treated as a set for
  346. // diffing purposes, so different orderings of the same elements will be
  347. // considered equal. Elements which are present on both sides of the
  348. // comparison but which have changed position will be reported with
  349. // ReportMoved(). Elements which only exist on one side or the other are
  350. // reported with ReportAdded() and ReportDeleted() regardless of their
  351. // positions. ReportModified() is never used for this repeated field. If
  352. // the only differences between the compared messages is that some fields
  353. // have been moved, then the comparison returns true.
  354. //
  355. // Note that despite the name of this method, this is really
  356. // comparison as multisets: if one side of the comparison has a duplicate
  357. // in the repeated field but the other side doesn't, this will count as
  358. // a mismatch.
  359. //
  360. // If the scope of comparison is set to PARTIAL, then in addition to what's
  361. // above, extra values added to repeated fields of the second message will
  362. // not cause the comparison to fail.
  363. //
  364. // Note that set comparison is currently O(k * n^2) (where n is the total
  365. // number of elements, and k is the average size of each element). In theory
  366. // it could be made O(n * k) with a more complex hashing implementation. Feel
  367. // free to contribute one if the current implementation is too slow for you.
  368. // If partial matching is also enabled, the time complexity will be O(k * n^2
  369. // + n^3) in which n^3 is the time complexity of the maximum matching
  370. // algorithm.
  371. //
  372. // REQUIRES: field->is_repeated() and field not registered with TreatAsList
  373. void TreatAsSet(const FieldDescriptor* field);
  374. void TreatAsSmartSet(const FieldDescriptor* field);
  375. // The elements of the given repeated field will be treated as a list for
  376. // diffing purposes, so different orderings of the same elements will NOT be
  377. // considered equal.
  378. //
  379. // REQUIRED: field->is_repeated() and field not registered with TreatAsSet
  380. void TreatAsList(const FieldDescriptor* field);
  381. // Note that the complexity is similar to treating as SET.
  382. void TreatAsSmartList(const FieldDescriptor* field);
  383. // The elements of the given repeated field will be treated as a map for
  384. // diffing purposes, with |key| being the map key. Thus, elements with the
  385. // same key will be compared even if they do not appear at the same index.
  386. // Differences are reported similarly to TreatAsSet(), except that
  387. // ReportModified() is used to report elements with the same key but
  388. // different values. Note that if an element is both moved and modified,
  389. // only ReportModified() will be called. As with TreatAsSet, if the only
  390. // differences between the compared messages is that some fields have been
  391. // moved, then the comparison returns true. See TreatAsSet for notes on
  392. // performance.
  393. //
  394. // REQUIRES: field->is_repeated()
  395. // REQUIRES: field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE
  396. // REQUIRES: key->containing_type() == field->message_type()
  397. void TreatAsMap(const FieldDescriptor* field, const FieldDescriptor* key);
  398. // Same as TreatAsMap except that this method will use multiple fields as
  399. // the key in comparison. All specified fields in 'key_fields' should be
  400. // present in the compared elements. Two elements will be treated as having
  401. // the same key iff they have the same value for every specified field. There
  402. // are two steps in the comparison process. The first one is key matching.
  403. // Every element from one message will be compared to every element from
  404. // the other message. Only fields in 'key_fields' are compared in this step
  405. // to decide if two elements have the same key. The second step is value
  406. // comparison. Those pairs of elements with the same key (with equal value
  407. // for every field in 'key_fields') will be compared in this step.
  408. // Time complexity of the first step is O(s * m * n ^ 2) where s is the
  409. // average size of the fields specified in 'key_fields', m is the number of
  410. // fields in 'key_fields' and n is the number of elements. If partial
  411. // matching is enabled, an extra O(n^3) will be incured by the maximum
  412. // matching algorithm. The second step is O(k * n) where k is the average
  413. // size of each element.
  414. void TreatAsMapWithMultipleFieldsAsKey(
  415. const FieldDescriptor* field,
  416. const std::vector<const FieldDescriptor*>& key_fields);
  417. // Same as TreatAsMapWithMultipleFieldsAsKey, except that each of the field
  418. // do not necessarily need to be a direct subfield. Each element in
  419. // key_field_paths indicate a path from the message being compared, listing
  420. // successive subfield to reach the key field.
  421. //
  422. // REQUIRES:
  423. // for key_field_path in key_field_paths:
  424. // key_field_path[0]->containing_type() == field->message_type()
  425. // for i in [0, key_field_path.size() - 1):
  426. // key_field_path[i+1]->containing_type() ==
  427. // key_field_path[i]->message_type()
  428. // key_field_path[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE
  429. // !key_field_path[i]->is_repeated()
  430. void TreatAsMapWithMultipleFieldPathsAsKey(
  431. const FieldDescriptor* field,
  432. const std::vector<std::vector<const FieldDescriptor*> >& key_field_paths);
  433. // Uses a custom MapKeyComparator to determine if two elements have the same
  434. // key when comparing a repeated field as a map.
  435. // The caller is responsible to delete the key_comparator.
  436. // This method varies from TreatAsMapWithMultipleFieldsAsKey only in the
  437. // first key matching step. Rather than comparing some specified fields, it
  438. // will invoke the IsMatch method of the given 'key_comparator' to decide if
  439. // two elements have the same key.
  440. void TreatAsMapUsingKeyComparator(const FieldDescriptor* field,
  441. const MapKeyComparator* key_comparator);
  442. // Initiates and returns a new instance of MultipleFieldsMapKeyComparator.
  443. MapKeyComparator* CreateMultipleFieldsMapKeyComparator(
  444. const std::vector<std::vector<const FieldDescriptor*> >& key_field_paths);
  445. // Add a custom ignore criteria that is evaluated in addition to the
  446. // ignored fields added with IgnoreField.
  447. // Takes ownership of ignore_criteria.
  448. void AddIgnoreCriteria(IgnoreCriteria* ignore_criteria);
  449. // Indicates that any field with the given descriptor should be
  450. // ignored for the purposes of comparing two messages. This applies
  451. // to fields nested in the message structure as well as top level
  452. // ones. When the MessageDifferencer encounters an ignored field,
  453. // ReportIgnored is called on the reporter, if one is specified.
  454. //
  455. // The only place where the field's 'ignored' status is not applied is when
  456. // it is being used as a key in a field passed to TreatAsMap or is one of
  457. // the fields passed to TreatAsMapWithMultipleFieldsAsKey.
  458. // In this case it is compared in key matching but after that it's ignored
  459. // in value comparison.
  460. void IgnoreField(const FieldDescriptor* field);
  461. // Sets the field comparator used to determine differences between protocol
  462. // buffer fields. By default it's set to a DefaultFieldComparator instance.
  463. // MessageDifferencer doesn't take ownership over the passed object.
  464. // Note that this method must be called before Compare for the comparator to
  465. // be used.
  466. void set_field_comparator(FieldComparator* comparator);
  467. // DEPRECATED. Pass a DefaultFieldComparator instance instead.
  468. // Sets the fraction and margin for the float comparison of a given field.
  469. // Uses MathUtil::WithinFractionOrMargin to compare the values.
  470. // NOTE: this method does nothing if differencer's field comparator has been
  471. // set to a custom object.
  472. //
  473. // REQUIRES: field->cpp_type == FieldDescriptor::CPPTYPE_DOUBLE or
  474. // field->cpp_type == FieldDescriptor::CPPTYPE_FLOAT
  475. // REQUIRES: float_comparison_ == APPROXIMATE
  476. void SetFractionAndMargin(const FieldDescriptor* field, double fraction,
  477. double margin);
  478. // Sets the type of comparison (as defined in the MessageFieldComparison
  479. // enumeration above) that is used by this differencer when determining how
  480. // to compare fields in messages.
  481. void set_message_field_comparison(MessageFieldComparison comparison);
  482. // Tells the differencer whether or not to report matches. This method must
  483. // be called before Compare. The default for a new differencer is false.
  484. void set_report_matches(bool report_matches) {
  485. report_matches_ = report_matches;
  486. }
  487. // Tells the differencer whether or not to report moves (in a set or map
  488. // repeated field). This method must be called before Compare. The default for
  489. // a new differencer is true.
  490. void set_report_moves(bool report_moves) { report_moves_ = report_moves; }
  491. // Tells the differencer whether or not to report ignored values. This method
  492. // must be called before Compare. The default for a new differencer is true.
  493. void set_report_ignores(bool report_ignores) {
  494. report_ignores_ = report_ignores;
  495. }
  496. // Sets the scope of the comparison (as defined in the Scope enumeration
  497. // above) that is used by this differencer when determining which fields to
  498. // compare between the messages.
  499. void set_scope(Scope scope);
  500. // Returns the current scope used by this differencer.
  501. Scope scope();
  502. // DEPRECATED. Pass a DefaultFieldComparator instance instead.
  503. // Sets the type of comparison (as defined in the FloatComparison enumeration
  504. // above) that is used by this differencer when comparing float (and double)
  505. // fields in messages.
  506. // NOTE: this method does nothing if differencer's field comparator has been
  507. // set to a custom object.
  508. void set_float_comparison(FloatComparison comparison);
  509. // Sets the type of comparison for repeated field (as defined in the
  510. // RepeatedFieldComparison enumeration above) that is used by this
  511. // differencer when compare repeated fields in messages.
  512. void set_repeated_field_comparison(RepeatedFieldComparison comparison);
  513. // Compares the two specified messages, returning true if they are the same,
  514. // false otherwise. If this method returns false, any changes between the
  515. // two messages will be reported if a Reporter was specified via
  516. // ReportDifferencesTo (see also ReportDifferencesToString).
  517. //
  518. // This method REQUIRES that the two messages have the same
  519. // Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
  520. bool Compare(const Message& message1, const Message& message2);
  521. // Same as above, except comparing only the list of fields specified by the
  522. // two vectors of FieldDescriptors.
  523. bool CompareWithFields(
  524. const Message& message1, const Message& message2,
  525. const std::vector<const FieldDescriptor*>& message1_fields,
  526. const std::vector<const FieldDescriptor*>& message2_fields);
  527. // Automatically creates a reporter that will output the differences
  528. // found (if any) to the specified output string pointer. Note that this
  529. // method must be called before Compare.
  530. void ReportDifferencesToString(std::string* output);
  531. // Tells the MessageDifferencer to report differences via the specified
  532. // reporter. Note that this method must be called before Compare for
  533. // the reporter to be used. It is the responsibility of the caller to delete
  534. // this object.
  535. // If the provided pointer equals NULL, the MessageDifferencer stops reporting
  536. // differences to any previously set reporters or output strings.
  537. void ReportDifferencesTo(Reporter* reporter);
  538. // An implementation of the MessageDifferencer Reporter that outputs
  539. // any differences found in human-readable form to the supplied
  540. // ZeroCopyOutputStream or Printer. If a printer is used, the delimiter
  541. // *must* be '$'.
  542. //
  543. // WARNING: this reporter does not necessarily flush its output until it is
  544. // destroyed. As a result, it is not safe to assume the output is valid or
  545. // complete until after you destroy the reporter. For example, if you use a
  546. // StreamReporter to write to a StringOutputStream, the target string may
  547. // contain uninitialized data until the reporter is destroyed.
  548. class PROTOBUF_EXPORT StreamReporter : public Reporter {
  549. public:
  550. explicit StreamReporter(io::ZeroCopyOutputStream* output);
  551. explicit StreamReporter(io::Printer* printer); // delimiter '$'
  552. ~StreamReporter() override;
  553. // When set to true, the stream reporter will also output aggregates nodes
  554. // (i.e. messages and groups) whose subfields have been modified. When
  555. // false, will only report the individual subfields. Defaults to false.
  556. void set_report_modified_aggregates(bool report) {
  557. report_modified_aggregates_ = report;
  558. }
  559. // The following are implementations of the methods described above.
  560. void ReportAdded(const Message& message1, const Message& message2,
  561. const std::vector<SpecificField>& field_path) override;
  562. void ReportDeleted(const Message& message1, const Message& message2,
  563. const std::vector<SpecificField>& field_path) override;
  564. void ReportModified(const Message& message1, const Message& message2,
  565. const std::vector<SpecificField>& field_path) override;
  566. void ReportMoved(const Message& message1, const Message& message2,
  567. const std::vector<SpecificField>& field_path) override;
  568. void ReportMatched(const Message& message1, const Message& message2,
  569. const std::vector<SpecificField>& field_path) override;
  570. void ReportIgnored(const Message& message1, const Message& message2,
  571. const std::vector<SpecificField>& field_path) override;
  572. void ReportUnknownFieldIgnored(
  573. const Message& message1, const Message& message2,
  574. const std::vector<SpecificField>& field_path) override;
  575. protected:
  576. // Prints the specified path of fields to the buffer. message is used to
  577. // print map keys.
  578. virtual void PrintPath(const std::vector<SpecificField>& field_path,
  579. bool left_side, const Message& message);
  580. // Prints the specified path of fields to the buffer.
  581. virtual void PrintPath(const std::vector<SpecificField>& field_path,
  582. bool left_side);
  583. // Prints the value of fields to the buffer. left_side is true if the
  584. // given message is from the left side of the comparison, false if it
  585. // was the right. This is relevant only to decide whether to follow
  586. // unknown_field_index1 or unknown_field_index2 when an unknown field
  587. // is encountered in field_path.
  588. virtual void PrintValue(const Message& message,
  589. const std::vector<SpecificField>& field_path,
  590. bool left_side);
  591. // Prints the specified path of unknown fields to the buffer.
  592. virtual void PrintUnknownFieldValue(const UnknownField* unknown_field);
  593. // Just print a string
  594. void Print(const std::string& str);
  595. private:
  596. io::Printer* printer_;
  597. bool delete_printer_;
  598. bool report_modified_aggregates_;
  599. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StreamReporter);
  600. };
  601. private:
  602. friend class DefaultFieldComparator;
  603. // A MapKeyComparator to be used in TreatAsMapUsingKeyComparator.
  604. // Implementation of this class needs to do field value comparison which
  605. // relies on some private methods of MessageDifferencer. That's why this
  606. // class is declared as a nested class of MessageDifferencer.
  607. class MultipleFieldsMapKeyComparator;
  608. // A MapKeyComparator for use with map_entries.
  609. class PROTOBUF_EXPORT MapEntryKeyComparator : public MapKeyComparator {
  610. public:
  611. explicit MapEntryKeyComparator(MessageDifferencer* message_differencer);
  612. bool IsMatch(
  613. const Message& message1, const Message& message2,
  614. const std::vector<SpecificField>& parent_fields) const override;
  615. private:
  616. MessageDifferencer* message_differencer_;
  617. };
  618. // Returns true if field1's number() is less than field2's.
  619. static bool FieldBefore(const FieldDescriptor* field1,
  620. const FieldDescriptor* field2);
  621. // Retrieve all the set fields, including extensions.
  622. FieldDescriptorArray RetrieveFields(const Message& message,
  623. bool base_message);
  624. // Combine the two lists of fields into the combined_fields output vector.
  625. // All fields present in both lists will always be included in the combined
  626. // list. Fields only present in one of the lists will only appear in the
  627. // combined list if the corresponding fields_scope option is set to FULL.
  628. FieldDescriptorArray CombineFields(const FieldDescriptorArray& fields1,
  629. Scope fields1_scope,
  630. const FieldDescriptorArray& fields2,
  631. Scope fields2_scope);
  632. // Internal version of the Compare method which performs the actual
  633. // comparison. The parent_fields vector is a vector containing field
  634. // descriptors of all fields accessed to get to this comparison operation
  635. // (i.e. if the current message is an embedded message, the parent_fields
  636. // vector will contain the field that has this embedded message).
  637. bool Compare(const Message& message1, const Message& message2,
  638. std::vector<SpecificField>* parent_fields);
  639. // Compares all the unknown fields in two messages.
  640. bool CompareUnknownFields(const Message& message1, const Message& message2,
  641. const UnknownFieldSet&, const UnknownFieldSet&,
  642. std::vector<SpecificField>* parent_fields);
  643. // Compares the specified messages for the requested field lists. The field
  644. // lists are modified depending on comparison settings, and then passed to
  645. // CompareWithFieldsInternal.
  646. bool CompareRequestedFieldsUsingSettings(
  647. const Message& message1, const Message& message2,
  648. const FieldDescriptorArray& message1_fields,
  649. const FieldDescriptorArray& message2_fields,
  650. std::vector<SpecificField>* parent_fields);
  651. // Compares the specified messages with the specified field lists.
  652. bool CompareWithFieldsInternal(const Message& message1,
  653. const Message& message2,
  654. const FieldDescriptorArray& message1_fields,
  655. const FieldDescriptorArray& message2_fields,
  656. std::vector<SpecificField>* parent_fields);
  657. // Compares the repeated fields, and report the error.
  658. bool CompareRepeatedField(const Message& message1, const Message& message2,
  659. const FieldDescriptor* field,
  660. std::vector<SpecificField>* parent_fields);
  661. // Shorthand for CompareFieldValueUsingParentFields with NULL parent_fields.
  662. bool CompareFieldValue(const Message& message1, const Message& message2,
  663. const FieldDescriptor* field, int index1, int index2);
  664. // Compares the specified field on the two messages, returning
  665. // true if they are the same, false otherwise. For repeated fields,
  666. // this method only compares the value in the specified index. This method
  667. // uses Compare functions to recurse into submessages.
  668. // The parent_fields vector is used in calls to a Reporter instance calls.
  669. // It can be NULL, in which case the MessageDifferencer will create new
  670. // list of parent messages if it needs to recursively compare the given field.
  671. // To avoid confusing users you should not set it to NULL unless you modified
  672. // Reporter to handle the change of parent_fields correctly.
  673. bool CompareFieldValueUsingParentFields(
  674. const Message& message1, const Message& message2,
  675. const FieldDescriptor* field, int index1, int index2,
  676. std::vector<SpecificField>* parent_fields);
  677. // Compares the specified field on the two messages, returning comparison
  678. // result, as returned by appropriate FieldComparator.
  679. FieldComparator::ComparisonResult GetFieldComparisonResult(
  680. const Message& message1, const Message& message2,
  681. const FieldDescriptor* field, int index1, int index2,
  682. const FieldContext* field_context);
  683. // Check if the two elements in the repeated field are match to each other.
  684. // if the key_comprator is NULL, this function returns true when the two
  685. // elements are equal.
  686. bool IsMatch(const FieldDescriptor* repeated_field,
  687. const MapKeyComparator* key_comparator, const Message* message1,
  688. const Message* message2,
  689. const std::vector<SpecificField>& parent_fields,
  690. Reporter* reporter, int index1, int index2);
  691. // Returns true when this repeated field has been configured to be treated
  692. // as a Set / SmartSet / SmartList.
  693. bool IsTreatedAsSet(const FieldDescriptor* field);
  694. bool IsTreatedAsSmartSet(const FieldDescriptor* field);
  695. bool IsTreatedAsSmartList(const FieldDescriptor* field);
  696. // When treating as SMART_LIST, it uses MatchIndicesPostProcessorForSmartList
  697. // by default to find the longest matching sequence from the first matching
  698. // element. The callback takes two vectors showing the matching indices from
  699. // the other vector, where -1 means an unmatch.
  700. void SetMatchIndicesForSmartListCallback(
  701. std::function<void(std::vector<int>*, std::vector<int>*)> callback);
  702. // Returns true when this repeated field is to be compared as a subset, ie.
  703. // has been configured to be treated as a set or map and scope is set to
  704. // PARTIAL.
  705. bool IsTreatedAsSubset(const FieldDescriptor* field);
  706. // Returns true if this field is to be ignored when this
  707. // MessageDifferencer compares messages.
  708. bool IsIgnored(const Message& message1, const Message& message2,
  709. const FieldDescriptor* field,
  710. const std::vector<SpecificField>& parent_fields);
  711. // Returns true if this unknown field is to be ignored when this
  712. // MessageDifferencer compares messages.
  713. bool IsUnknownFieldIgnored(const Message& message1, const Message& message2,
  714. const SpecificField& field,
  715. const std::vector<SpecificField>& parent_fields);
  716. // Returns MapKeyComparator* when this field has been configured to be treated
  717. // as a map or its is_map() return true. If not, returns NULL.
  718. const MapKeyComparator* GetMapKeyComparator(
  719. const FieldDescriptor* field) const;
  720. // Attempts to match indices of a repeated field, so that the contained values
  721. // match. Clears output vectors and sets their values to indices of paired
  722. // messages, ie. if message1[0] matches message2[1], then match_list1[0] == 1
  723. // and match_list2[1] == 0. The unmatched indices are indicated by -1.
  724. // Assumes the repeated field is not treated as a simple list.
  725. // This method returns false if the match failed. However, it doesn't mean
  726. // that the comparison succeeds when this method returns true (you need to
  727. // double-check in this case).
  728. bool MatchRepeatedFieldIndices(
  729. const Message& message1, const Message& message2,
  730. const FieldDescriptor* repeated_field,
  731. const MapKeyComparator* key_comparator,
  732. const std::vector<SpecificField>& parent_fields,
  733. std::vector<int>* match_list1, std::vector<int>* match_list2);
  734. // If "any" is of type google.protobuf.Any, extract its payload using
  735. // DynamicMessageFactory and store in "data".
  736. bool UnpackAny(const Message& any, std::unique_ptr<Message>* data);
  737. // Checks if index is equal to new_index in all the specific fields.
  738. static bool CheckPathChanged(const std::vector<SpecificField>& parent_fields);
  739. // CHECKs that the given repeated field can be compared according to
  740. // new_comparison.
  741. void CheckRepeatedFieldComparisons(
  742. const FieldDescriptor* field,
  743. const RepeatedFieldComparison& new_comparison);
  744. // Defines a map between field descriptors and their MapKeyComparators.
  745. // Used for repeated fields when they are configured as TreatAsMap.
  746. typedef std::map<const FieldDescriptor*, const MapKeyComparator*>
  747. FieldKeyComparatorMap;
  748. // Defines a set to store field descriptors. Used for repeated fields when
  749. // they are configured as TreatAsSet.
  750. typedef std::set<const FieldDescriptor*> FieldSet;
  751. typedef std::map<const FieldDescriptor*, RepeatedFieldComparison> FieldMap;
  752. Reporter* reporter_;
  753. DefaultFieldComparator default_field_comparator_;
  754. FieldComparator* field_comparator_;
  755. MessageFieldComparison message_field_comparison_;
  756. Scope scope_;
  757. RepeatedFieldComparison repeated_field_comparison_;
  758. FieldMap repeated_field_comparisons_;
  759. // Keeps track of MapKeyComparators that are created within
  760. // MessageDifferencer. These MapKeyComparators should be deleted
  761. // before MessageDifferencer is destroyed.
  762. // When TreatAsMap or TreatAsMapWithMultipleFieldsAsKey is called, we don't
  763. // store the supplied FieldDescriptors directly. Instead, a new
  764. // MapKeyComparator is created for comparison purpose.
  765. std::vector<MapKeyComparator*> owned_key_comparators_;
  766. FieldKeyComparatorMap map_field_key_comparator_;
  767. MapEntryKeyComparator map_entry_key_comparator_;
  768. std::vector<IgnoreCriteria*> ignore_criteria_;
  769. // Reused multiple times in RetrieveFields to avoid extra allocations
  770. std::vector<const FieldDescriptor*> tmp_message_fields_;
  771. FieldSet ignored_fields_;
  772. bool report_matches_;
  773. bool report_moves_;
  774. bool report_ignores_;
  775. std::string* output_string_;
  776. // Callback to post-process the matched indices to support SMART_LIST.
  777. std::function<void(std::vector<int>*, std::vector<int>*)>
  778. match_indices_for_smart_list_callback_;
  779. std::unique_ptr<DynamicMessageFactory> dynamic_message_factory_;
  780. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageDifferencer);
  781. };
  782. // This class provides extra information to the FieldComparator::Compare
  783. // function.
  784. class PROTOBUF_EXPORT FieldContext {
  785. public:
  786. explicit FieldContext(
  787. std::vector<MessageDifferencer::SpecificField>* parent_fields)
  788. : parent_fields_(parent_fields) {}
  789. std::vector<MessageDifferencer::SpecificField>* parent_fields() const {
  790. return parent_fields_;
  791. }
  792. private:
  793. std::vector<MessageDifferencer::SpecificField>* parent_fields_;
  794. };
  795. } // namespace util
  796. } // namespace protobuf
  797. } // namespace google
  798. #include <google/protobuf/port_undef.inc>
  799. #endif // GOOGLE_PROTOBUF_UTIL_MESSAGE_DIFFERENCER_H__