1 // Copyright 2009 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.
5 // Deep equality test via reflection
10 // During deepValueEqual, must keep track of checks that are
11 // in progress. The comparison algorithm assumes that all
12 // checks in progress are true when it reencounters them.
13 // Visited are stored in a map indexed by 17 * a1 + a2;
21 // Tests for deep equality using reflected types. The map argument tracks
22 // comparisons that have already been seen, which allows short circuiting on
24 func deepValueEqual(v1
, v2 Value
, visited
map[uintptr]*visit
, depth
int) bool {
25 if v1
== nil || v2
== nil {
28 if v1
.Type() != v2
.Type() {
32 // if depth > 10 { panic("deepValueEqual") } // for debugging
37 // Canonicalize order to reduce number of entries in visited.
38 addr1
, addr2
= addr2
, addr1
41 // Short circuit if references are identical ...
46 // ... or already seen
50 for p
:= seen
; p
!= nil; p
= p
.next
{
51 if p
.a1
== addr1
&& p
.a2
== addr2
&& p
.typ
== typ
{
56 // Remember for later.
57 visited
[h
] = &visit
{addr1
, addr2
, typ
, seen
}
59 switch v
:= v1
.(type) {
62 arr2
:= v2
.(*ArrayValue
)
63 if arr1
.Len() != arr2
.Len() {
66 for i
:= 0; i
< arr1
.Len(); i
++ {
67 if !deepValueEqual(arr1
.Elem(i
), arr2
.Elem(i
), visited
, depth
+1) {
74 arr2
:= v2
.(*SliceValue
)
75 if arr1
.Len() != arr2
.Len() {
78 for i
:= 0; i
< arr1
.Len(); i
++ {
79 if !deepValueEqual(arr1
.Elem(i
), arr2
.Elem(i
), visited
, depth
+1) {
87 if i1
== nil || i2
== nil {
90 return deepValueEqual(NewValue(i1
), NewValue(i2
), visited
, depth
+1)
92 return deepValueEqual(v
.Elem(), v2
.(*PtrValue
).Elem(), visited
, depth
+1)
95 struct2
:= v2
.(*StructValue
)
96 for i
, n
:= 0, v
.NumField(); i
< n
; i
++ {
97 if !deepValueEqual(struct1
.Field(i
), struct2
.Field(i
), visited
, depth
+1) {
104 map2
:= v2
.(*MapValue
)
105 if map1
.Len() != map2
.Len() {
108 for _
, k
:= range map1
.Keys() {
109 if !deepValueEqual(map1
.Elem(k
), map2
.Elem(k
), visited
, depth
+1) {
115 // Normal equality suffices
116 return v1
.Interface() == v2
.Interface()
122 // DeepEqual tests for deep equality. It uses normal == equality where possible
123 // but will scan members of arrays, slices, and fields of structs. It correctly
124 // handles recursive types.
125 func DeepEqual(a1
, a2
interface{}) bool {
126 if a1
== nil || a2
== nil {
131 if v1
.Type() != v2
.Type() {
134 return deepValueEqual(v1
, v2
, make(map[uintptr]*visit
), 0)