message_differencer.h 46 KB

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