Black Lives Matter. Support the Equal Justice Initiative.

Source file src/reflect/deepequal.go

Documentation: reflect

     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.
     4  
     5  // Deep equality test via reflection
     6  
     7  package reflect
     8  
     9  import "unsafe"
    10  
    11  // During deepValueEqual, must keep track of checks that are
    12  // in progress. The comparison algorithm assumes that all
    13  // checks in progress are true when it reencounters them.
    14  // Visited comparisons are stored in a map indexed by visit.
    15  type visit struct {
    16  	a1  unsafe.Pointer
    17  	a2  unsafe.Pointer
    18  	typ Type
    19  }
    20  
    21  // Tests for deep equality using reflected types. The map argument tracks
    22  // comparisons that have already been seen, which allows short circuiting on
    23  // recursive types.
    24  func deepValueEqual(v1, v2 Value, visited map[visit]bool, depth int) bool {
    25  	if !v1.IsValid() || !v2.IsValid() {
    26  		return v1.IsValid() == v2.IsValid()
    27  	}
    28  	if v1.Type() != v2.Type() {
    29  		return false
    30  	}
    31  
    32  	// if depth > 10 { panic("deepValueEqual") }	// for debugging
    33  
    34  	// We want to avoid putting more in the visited map than we need to.
    35  	// For any possible reference cycle that might be encountered,
    36  	// hard(v1, v2) needs to return true for at least one of the types in the cycle,
    37  	// and it's safe and valid to get Value's internal pointer.
    38  	hard := func(v1, v2 Value) bool {
    39  		switch v1.Kind() {
    40  		case Ptr:
    41  			if v1.typ.ptrdata == 0 {
    42  				// go:notinheap pointers can't be cyclic.
    43  				// At least, all of our current uses of go:notinheap have
    44  				// that property. The runtime ones aren't cyclic (and we don't use
    45  				// DeepEqual on them anyway), and the cgo-generated ones are
    46  				// all empty structs.
    47  				return false
    48  			}
    49  			fallthrough
    50  		case Map, Slice, Interface:
    51  			// Nil pointers cannot be cyclic. Avoid putting them in the visited map.
    52  			return !v1.IsNil() && !v2.IsNil()
    53  		}
    54  		return false
    55  	}
    56  
    57  	if hard(v1, v2) {
    58  		// For a Ptr or Map value, we need to check flagIndir,
    59  		// which we do by calling the pointer method.
    60  		// For Slice or Interface, flagIndir is always set,
    61  		// and using v.ptr suffices.
    62  		ptrval := func(v Value) unsafe.Pointer {
    63  			switch v.Kind() {
    64  			case Ptr, Map:
    65  				return v.pointer()
    66  			default:
    67  				return v.ptr
    68  			}
    69  		}
    70  		addr1 := ptrval(v1)
    71  		addr2 := ptrval(v2)
    72  		if uintptr(addr1) > uintptr(addr2) {
    73  			// Canonicalize order to reduce number of entries in visited.
    74  			// Assumes non-moving garbage collector.
    75  			addr1, addr2 = addr2, addr1
    76  		}
    77  
    78  		// Short circuit if references are already seen.
    79  		typ := v1.Type()
    80  		v := visit{addr1, addr2, typ}
    81  		if visited[v] {
    82  			return true
    83  		}
    84  
    85  		// Remember for later.
    86  		visited[v] = true
    87  	}
    88  
    89  	switch v1.Kind() {
    90  	case Array:
    91  		for i := 0; i < v1.Len(); i++ {
    92  			if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
    93  				return false
    94  			}
    95  		}
    96  		return true
    97  	case Slice:
    98  		if v1.IsNil() != v2.IsNil() {
    99  			return false
   100  		}
   101  		if v1.Len() != v2.Len() {
   102  			return false
   103  		}
   104  		if v1.Pointer() == v2.Pointer() {
   105  			return true
   106  		}
   107  		for i := 0; i < v1.Len(); i++ {
   108  			if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
   109  				return false
   110  			}
   111  		}
   112  		return true
   113  	case Interface:
   114  		if v1.IsNil() || v2.IsNil() {
   115  			return v1.IsNil() == v2.IsNil()
   116  		}
   117  		return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
   118  	case Ptr:
   119  		if v1.Pointer() == v2.Pointer() {
   120  			return true
   121  		}
   122  		return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
   123  	case Struct:
   124  		for i, n := 0, v1.NumField(); i < n; i++ {
   125  			if !deepValueEqual(v1.Field(i), v2.Field(i), visited, depth+1) {
   126  				return false
   127  			}
   128  		}
   129  		return true
   130  	case Map:
   131  		if v1.IsNil() != v2.IsNil() {
   132  			return false
   133  		}
   134  		if v1.Len() != v2.Len() {
   135  			return false
   136  		}
   137  		if v1.Pointer() == v2.Pointer() {
   138  			return true
   139  		}
   140  		for _, k := range v1.MapKeys() {
   141  			val1 := v1.MapIndex(k)
   142  			val2 := v2.MapIndex(k)
   143  			if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(val1, val2, visited, depth+1) {
   144  				return false
   145  			}
   146  		}
   147  		return true
   148  	case Func:
   149  		if v1.IsNil() && v2.IsNil() {
   150  			return true
   151  		}
   152  		// Can't do better than this:
   153  		return false
   154  	default:
   155  		// Normal equality suffices
   156  		return valueInterface(v1, false) == valueInterface(v2, false)
   157  	}
   158  }
   159  
   160  // DeepEqual reports whether x and y are ``deeply equal,'' defined as follows.
   161  // Two values of identical type are deeply equal if one of the following cases applies.
   162  // Values of distinct types are never deeply equal.
   163  //
   164  // Array values are deeply equal when their corresponding elements are deeply equal.
   165  //
   166  // Struct values are deeply equal if their corresponding fields,
   167  // both exported and unexported, are deeply equal.
   168  //
   169  // Func values are deeply equal if both are nil; otherwise they are not deeply equal.
   170  //
   171  // Interface values are deeply equal if they hold deeply equal concrete values.
   172  //
   173  // Map values are deeply equal when all of the following are true:
   174  // they are both nil or both non-nil, they have the same length,
   175  // and either they are the same map object or their corresponding keys
   176  // (matched using Go equality) map to deeply equal values.
   177  //
   178  // Pointer values are deeply equal if they are equal using Go's == operator
   179  // or if they point to deeply equal values.
   180  //
   181  // Slice values are deeply equal when all of the following are true:
   182  // they are both nil or both non-nil, they have the same length,
   183  // and either they point to the same initial entry of the same underlying array
   184  // (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
   185  // Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil))
   186  // are not deeply equal.
   187  //
   188  // Other values - numbers, bools, strings, and channels - are deeply equal
   189  // if they are equal using Go's == operator.
   190  //
   191  // In general DeepEqual is a recursive relaxation of Go's == operator.
   192  // However, this idea is impossible to implement without some inconsistency.
   193  // Specifically, it is possible for a value to be unequal to itself,
   194  // either because it is of func type (uncomparable in general)
   195  // or because it is a floating-point NaN value (not equal to itself in floating-point comparison),
   196  // or because it is an array, struct, or interface containing
   197  // such a value.
   198  // On the other hand, pointer values are always equal to themselves,
   199  // even if they point at or contain such problematic values,
   200  // because they compare equal using Go's == operator, and that
   201  // is a sufficient condition to be deeply equal, regardless of content.
   202  // DeepEqual has been defined so that the same short-cut applies
   203  // to slices and maps: if x and y are the same slice or the same map,
   204  // they are deeply equal regardless of content.
   205  //
   206  // As DeepEqual traverses the data values it may find a cycle. The
   207  // second and subsequent times that DeepEqual compares two pointer
   208  // values that have been compared before, it treats the values as
   209  // equal rather than examining the values to which they point.
   210  // This ensures that DeepEqual terminates.
   211  func DeepEqual(x, y interface{}) bool {
   212  	if x == nil || y == nil {
   213  		return x == y
   214  	}
   215  	v1 := ValueOf(x)
   216  	v2 := ValueOf(y)
   217  	if v1.Type() != v2.Type() {
   218  		return false
   219  	}
   220  	return deepValueEqual(v1, v2, make(map[visit]bool), 0)
   221  }
   222  

View as plain text