blob: 1a0be1b03c73d597c89222430c6d9659c3b6caf5 [file] [log] [blame]
Naveen Sampath04696f72022-06-13 15:19:14 +05301// 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 (
Naveen Sampath04696f72022-06-13 15:19:14 +05308 "reflect"
9
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053010 "google.golang.org/protobuf/reflect/protoreflect"
Naveen Sampath04696f72022-06-13 15:19:14 +053011)
12
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053013// Equal reports whether two messages are equal,
14// by recursively comparing the fields of the message.
Naveen Sampath04696f72022-06-13 15:19:14 +053015//
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053016// - Bytes fields are equal if they contain identical bytes.
17// Empty bytes (regardless of nil-ness) are considered equal.
Naveen Sampath04696f72022-06-13 15:19:14 +053018//
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053019// - 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.
Naveen Sampath04696f72022-06-13 15:19:14 +053041func Equal(x, y Message) bool {
42 if x == nil || y == nil {
43 return x == nil && y == nil
44 }
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053045 if reflect.TypeOf(x).Kind() == reflect.Ptr && x == y {
46 // Avoid an expensive comparison if both inputs are identical pointers.
47 return true
48 }
Naveen Sampath04696f72022-06-13 15:19:14 +053049 mx := x.ProtoReflect()
50 my := y.ProtoReflect()
51 if mx.IsValid() != my.IsValid() {
52 return false
53 }
Akash Reddy Kankanala105581b2024-09-11 05:20:38 +053054 vx := protoreflect.ValueOfMessage(mx)
55 vy := protoreflect.ValueOfMessage(my)
56 return vx.Equal(vy)
Naveen Sampath04696f72022-06-13 15:19:14 +053057}