equal.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package proto
  5. import (
  6. "reflect"
  7. "google.golang.org/protobuf/reflect/protoreflect"
  8. "google.golang.org/protobuf/runtime/protoiface"
  9. )
  10. // Equal reports whether two messages are equal,
  11. // by recursively comparing the fields of the message.
  12. //
  13. // - Bytes fields are equal if they contain identical bytes.
  14. // Empty bytes (regardless of nil-ness) are considered equal.
  15. //
  16. // - Floating-point fields are equal if they contain the same value.
  17. // Unlike the == operator, a NaN is equal to another NaN.
  18. //
  19. // - Other scalar fields are equal if they contain the same value.
  20. //
  21. // - Message fields are equal if they have
  22. // the same set of populated known and extension field values, and
  23. // the same set of unknown fields values.
  24. //
  25. // - Lists are equal if they are the same length and
  26. // each corresponding element is equal.
  27. //
  28. // - Maps are equal if they have the same set of keys and
  29. // the corresponding value for each key is equal.
  30. //
  31. // An invalid message is not equal to a valid message.
  32. // An invalid message is only equal to another invalid message of the
  33. // same type. An invalid message often corresponds to a nil pointer
  34. // of the concrete message type. For example, (*pb.M)(nil) is not equal
  35. // to &pb.M{}.
  36. // If two valid messages marshal to the same bytes under deterministic
  37. // serialization, then Equal is guaranteed to report true.
  38. func Equal(x, y Message) bool {
  39. if x == nil || y == nil {
  40. return x == nil && y == nil
  41. }
  42. if reflect.TypeOf(x).Kind() == reflect.Ptr && x == y {
  43. // Avoid an expensive comparison if both inputs are identical pointers.
  44. return true
  45. }
  46. mx := x.ProtoReflect()
  47. my := y.ProtoReflect()
  48. if mx.IsValid() != my.IsValid() {
  49. return false
  50. }
  51. // Only one of the messages needs to implement the fast-path for it to work.
  52. pmx := protoMethods(mx)
  53. pmy := protoMethods(my)
  54. if pmx != nil && pmy != nil && pmx.Equal != nil && pmy.Equal != nil {
  55. return pmx.Equal(protoiface.EqualInput{MessageA: mx, MessageB: my}).Equal
  56. }
  57. vx := protoreflect.ValueOfMessage(mx)
  58. vy := protoreflect.ValueOfMessage(my)
  59. return vx.Equal(vy)
  60. }