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