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

58 lines
1.9 KiB

  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. )
  9. // Equal reports whether two messages are equal,
  10. // by recursively comparing the fields of the message.
  11. //
  12. // - Bytes fields are equal if they contain identical bytes.
  13. // Empty bytes (regardless of nil-ness) are considered equal.
  14. //
  15. // - Floating-point fields are equal if they contain the same value.
  16. // Unlike the == operator, a NaN is equal to another NaN.
  17. //
  18. // - Other scalar fields are equal if they contain the same value.
  19. //
  20. // - Message fields are equal if they have
  21. // the same set of populated known and extension field values, and
  22. // the same set of unknown fields values.
  23. //
  24. // - Lists are equal if they are the same length and
  25. // each corresponding element is equal.
  26. //
  27. // - Maps are equal if they have the same set of keys and
  28. // the corresponding value for each key is equal.
  29. //
  30. // An invalid message is not equal to a valid message.
  31. // An invalid message is only equal to another invalid message of the
  32. // same type. An invalid message often corresponds to a nil pointer
  33. // of the concrete message type. For example, (*pb.M)(nil) is not equal
  34. // to &pb.M{}.
  35. // If two valid messages marshal to the same bytes under deterministic
  36. // serialization, then Equal is guaranteed to report true.
  37. func Equal(x, y Message) bool {
  38. if x == nil || y == nil {
  39. return x == nil && y == nil
  40. }
  41. if reflect.TypeOf(x).Kind() == reflect.Ptr && x == y {
  42. // Avoid an expensive comparison if both inputs are identical pointers.
  43. return true
  44. }
  45. mx := x.ProtoReflect()
  46. my := y.ProtoReflect()
  47. if mx.IsValid() != my.IsValid() {
  48. return false
  49. }
  50. vx := protoreflect.ValueOfMessage(mx)
  51. vy := protoreflect.ValueOfMessage(my)
  52. return vx.Equal(vy)
  53. }