message_differencer.h 46 KB

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