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 Map, Slice, Ptr, Interface:
    41  			// Nil pointers cannot be cyclic. Avoid putting them in the visited map.
    42  			return !v1.IsNil() && !v2.IsNil()
    43  		}
    44  		return false
    45  	}
    46  
    47  	if hard(v1, v2) {
    48  		// For a Ptr or Map value, we need to check flagIndir,
    49  		// which we do by calling the pointer method.
    50  		// For Slice or Interface, flagIndir is always set,
    51  		// and using v.ptr suffices.
    52  		ptrval := func(v Value) unsafe.Pointer {
    53  			switch v.Kind() {
    54  			case Ptr, Map:
    55  				return v.pointer()
    56  			default:
    57  				return v.ptr
    58  			}
    59  		}
    60  		addr1 := ptrval(v1)
    61  		addr2 := ptrval(v2)
    62  		if uintptr(addr1) > uintptr(addr2) {
    63  			// Canonicalize order to reduce number of entries in visited.
    64  			// Assumes non-moving garbage collector.
    65  			addr1, addr2 = addr2, addr1
    66  		}
    67  
    68  		// Short circuit if references are already seen.
    69  		typ := v1.Type()
    70  		v := visit{addr1, addr2, typ}
    71  		if visited[v] {
    72  			return true
    73  		}
    74  
    75  		// Remember for later.
    76  		visited[v] = true
    77  	}
    78  
    79  	switch v1.Kind() {
    80  	case Array:
    81  		for i := 0; i < v1.Len(); i++ {
    82  			if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
    83  				return false
    84  			}
    85  		}
    86  		return true
    87  	case Slice:
    88  		if v1.IsNil() != v2.IsNil() {
    89  			return false
    90  		}
    91  		if v1.Len() != v2.Len() {
    92  			return false
    93  		}
    94  		if v1.Pointer() == v2.Pointer() {
    95  			return true
    96  		}
    97  		for i := 0; i < v1.Len(); i++ {
    98  			if !deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
    99  				return false
   100  			}
   101  		}
   102  		return true
   103  	case Interface:
   104  		if v1.IsNil() || v2.IsNil() {
   105  			return v1.IsNil() == v2.IsNil()
   106  		}
   107  		return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
   108  	case Ptr:
   109  		if v1.Pointer() == v2.Pointer() {
   110  			return true
   111  		}
   112  		return deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
   113  	case Struct:
   114  		for i, n := 0, v1.NumField(); i < n; i++ {
   115  			if !deepValueEqual(v1.Field(i), v2.Field(i), visited, depth+1) {
   116  				return false
   117  			}
   118  		}
   119  		return true
   120  	case Map:
   121  		if v1.IsNil() != v2.IsNil() {
   122  			return false
   123  		}
   124  		if v1.Len() != v2.Len() {
   125  			return false
   126  		}
   127  		if v1.Pointer() == v2.Pointer() {
   128  			return true
   129  		}
   130  		for _, k := range v1.MapKeys() {
   131  			val1 := v1.MapIndex(k)
   132  			val2 := v2.MapIndex(k)
   133  			if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(val1, val2, visited, depth+1) {
   134  				return false
   135  			}
   136  		}
   137  		return true
   138  	case Func:
   139  		if v1.IsNil() && v2.IsNil() {
   140  			return true
   141  		}
   142  		// Can't do better than this:
   143  		return false
   144  	default:
   145  		// Normal equality suffices
   146  		return valueInterface(v1, false) == valueInterface(v2, false)
   147  	}
   148  }
   149  
   150  // DeepEqual reports whether x and y are ``deeply equal,'' defined as follows.
   151  // Two values of identical type are deeply equal if one of the following cases applies.
   152  // Values of distinct types are never deeply equal.
   153  //
   154  // Array values are deeply equal when their corresponding elements are deeply equal.
   155  //
   156  // Struct values are deeply equal if their corresponding fields,
   157  // both exported and unexported, are deeply equal.
   158  //
   159  // Func values are deeply equal if both are nil; otherwise they are not deeply equal.
   160  //
   161  // Interface values are deeply equal if they hold deeply equal concrete values.
   162  //
   163  // Map values are deeply equal when all of the following are true:
   164  // they are both nil or both non-nil, they have the same length,
   165  // and either they are the same map object or their corresponding keys
   166  // (matched using Go equality) map to deeply equal values.
   167  //
   168  // Pointer values are deeply equal if they are equal using Go's == operator
   169  // or if they point to deeply equal values.
   170  //
   171  // Slice values are deeply equal when all of the following are true:
   172  // they are both nil or both non-nil, they have the same length,
   173  // and either they point to the same initial entry of the same underlying array
   174  // (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
   175  // Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil))
   176  // are not deeply equal.
   177  //
   178  // Other values - numbers, bools, strings, and channels - are deeply equal
   179  // if they are equal using Go's == operator.
   180  //
   181  // In general DeepEqual is a recursive relaxation of Go's == operator.
   182  // However, this idea is impossible to implement without some inconsistency.
   183  // Specifically, it is possible for a value to be unequal to itself,
   184  // either because it is of func type (uncomparable in general)
   185  // or because it is a floating-point NaN value (not equal to itself in floating-point comparison),
   186  // or because it is an array, struct, or interface containing
   187  // such a value.
   188  // On the other hand, pointer values are always equal to themselves,
   189  // even if they point at or contain such problematic values,
   190  // because they compare equal using Go's == operator, and that
   191  // is a sufficient condition to be deeply equal, regardless of content.
   192  // DeepEqual has been defined so that the same short-cut applies
   193  // to slices and maps: if x and y are the same slice or the same map,
   194  // they are deeply equal regardless of content.
   195  //
   196  // As DeepEqual traverses the data values it may find a cycle. The
   197  // second and subsequent times that DeepEqual compares two pointer
   198  // values that have been compared before, it treats the values as
   199  // equal rather than examining the values to which they point.
   200  // This ensures that DeepEqual terminates.
   201  func DeepEqual(x, y interface{}) bool {
   202  	if x == nil || y == nil {
   203  		return x == y
   204  	}
   205  	v1 := ValueOf(x)
   206  	v2 := ValueOf(y)
   207  	if v1.Type() != v2.Type() {
   208  		return false
   209  	}
   210  	return deepValueEqual(v1, v2, make(map[visit]bool), 0)
   211  }
   212  

View as plain text