Blame vendor/github.com/google/go-cmp/cmp/compare.go

Packit 63bb0d
// Copyright 2017, The Go Authors. All rights reserved.
Packit 63bb0d
// Use of this source code is governed by a BSD-style
Packit 63bb0d
// license that can be found in the LICENSE.md file.
Packit 63bb0d
Packit 63bb0d
// Package cmp determines equality of values.
Packit 63bb0d
//
Packit 63bb0d
// This package is intended to be a more powerful and safer alternative to
Packit 63bb0d
// reflect.DeepEqual for comparing whether two values are semantically equal.
Packit 63bb0d
//
Packit 63bb0d
// The primary features of cmp are:
Packit 63bb0d
//
Packit 63bb0d
// • When the default behavior of equality does not suit the needs of the test,
Packit 63bb0d
// custom equality functions can override the equality operation.
Packit 63bb0d
// For example, an equality function may report floats as equal so long as they
Packit 63bb0d
// are within some tolerance of each other.
Packit 63bb0d
//
Packit 63bb0d
// • Types that have an Equal method may use that method to determine equality.
Packit 63bb0d
// This allows package authors to determine the equality operation for the types
Packit 63bb0d
// that they define.
Packit 63bb0d
//
Packit 63bb0d
// • If no custom equality functions are used and no Equal method is defined,
Packit 63bb0d
// equality is determined by recursively comparing the primitive kinds on both
Packit 63bb0d
// values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported
Packit 63bb0d
// fields are not compared by default; they result in panics unless suppressed
Packit 63bb0d
// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared
Packit 63bb0d
// using the AllowUnexported option.
Packit 63bb0d
package cmp
Packit 63bb0d
Packit 63bb0d
import (
Packit 63bb0d
	"fmt"
Packit 63bb0d
	"reflect"
Packit 63bb0d
	"strings"
Packit 63bb0d
Packit 63bb0d
	"github.com/google/go-cmp/cmp/internal/diff"
Packit 63bb0d
	"github.com/google/go-cmp/cmp/internal/flags"
Packit 63bb0d
	"github.com/google/go-cmp/cmp/internal/function"
Packit 63bb0d
	"github.com/google/go-cmp/cmp/internal/value"
Packit 63bb0d
)
Packit 63bb0d
Packit 63bb0d
// Equal reports whether x and y are equal by recursively applying the
Packit 63bb0d
// following rules in the given order to x and y and all of their sub-values:
Packit 63bb0d
//
Packit 63bb0d
// • Let S be the set of all Ignore, Transformer, and Comparer options that
Packit 63bb0d
// remain after applying all path filters, value filters, and type filters.
Packit 63bb0d
// If at least one Ignore exists in S, then the comparison is ignored.
Packit 63bb0d
// If the number of Transformer and Comparer options in S is greater than one,
Packit 63bb0d
// then Equal panics because it is ambiguous which option to use.
Packit 63bb0d
// If S contains a single Transformer, then use that to transform the current
Packit 63bb0d
// values and recursively call Equal on the output values.
Packit 63bb0d
// If S contains a single Comparer, then use that to compare the current values.
Packit 63bb0d
// Otherwise, evaluation proceeds to the next rule.
Packit 63bb0d
//
Packit 63bb0d
// • If the values have an Equal method of the form "(T) Equal(T) bool" or
Packit 63bb0d
// "(T) Equal(I) bool" where T is assignable to I, then use the result of
Packit 63bb0d
// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and
Packit 63bb0d
// evaluation proceeds to the next rule.
Packit 63bb0d
//
Packit 63bb0d
// • Lastly, try to compare x and y based on their basic kinds.
Packit 63bb0d
// Simple kinds like booleans, integers, floats, complex numbers, strings, and
Packit 63bb0d
// channels are compared using the equivalent of the == operator in Go.
Packit 63bb0d
// Functions are only equal if they are both nil, otherwise they are unequal.
Packit 63bb0d
//
Packit 63bb0d
// Structs are equal if recursively calling Equal on all fields report equal.
Packit 63bb0d
// If a struct contains unexported fields, Equal panics unless an Ignore option
Packit 63bb0d
// (e.g., cmpopts.IgnoreUnexported) ignores that field or the AllowUnexported
Packit 63bb0d
// option explicitly permits comparing the unexported field.
Packit 63bb0d
//
Packit 63bb0d
// Slices are equal if they are both nil or both non-nil, where recursively
Packit 63bb0d
// calling Equal on all non-ignored slice or array elements report equal.
Packit 63bb0d
// Empty non-nil slices and nil slices are not equal; to equate empty slices,
Packit 63bb0d
// consider using cmpopts.EquateEmpty.
Packit 63bb0d
//
Packit 63bb0d
// Maps are equal if they are both nil or both non-nil, where recursively
Packit 63bb0d
// calling Equal on all non-ignored map entries report equal.
Packit 63bb0d
// Map keys are equal according to the == operator.
Packit 63bb0d
// To use custom comparisons for map keys, consider using cmpopts.SortMaps.
Packit 63bb0d
// Empty non-nil maps and nil maps are not equal; to equate empty maps,
Packit 63bb0d
// consider using cmpopts.EquateEmpty.
Packit 63bb0d
//
Packit 63bb0d
// Pointers and interfaces are equal if they are both nil or both non-nil,
Packit 63bb0d
// where they have the same underlying concrete type and recursively
Packit 63bb0d
// calling Equal on the underlying values reports equal.
Packit 63bb0d
func Equal(x, y interface{}, opts ...Option) bool {
Packit 63bb0d
	vx := reflect.ValueOf(x)
Packit 63bb0d
	vy := reflect.ValueOf(y)
Packit 63bb0d
Packit 63bb0d
	// If the inputs are different types, auto-wrap them in an empty interface
Packit 63bb0d
	// so that they have the same parent type.
Packit 63bb0d
	var t reflect.Type
Packit 63bb0d
	if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() {
Packit 63bb0d
		t = reflect.TypeOf((*interface{})(nil)).Elem()
Packit 63bb0d
		if vx.IsValid() {
Packit 63bb0d
			vvx := reflect.New(t).Elem()
Packit 63bb0d
			vvx.Set(vx)
Packit 63bb0d
			vx = vvx
Packit 63bb0d
		}
Packit 63bb0d
		if vy.IsValid() {
Packit 63bb0d
			vvy := reflect.New(t).Elem()
Packit 63bb0d
			vvy.Set(vy)
Packit 63bb0d
			vy = vvy
Packit 63bb0d
		}
Packit 63bb0d
	} else {
Packit 63bb0d
		t = vx.Type()
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	s := newState(opts)
Packit 63bb0d
	s.compareAny(&pathStep{t, vx, vy})
Packit 63bb0d
	return s.result.Equal()
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// Diff returns a human-readable report of the differences between two values.
Packit 63bb0d
// It returns an empty string if and only if Equal returns true for the same
Packit 63bb0d
// input values and options.
Packit 63bb0d
//
Packit 63bb0d
// The output is displayed as a literal in pseudo-Go syntax.
Packit 63bb0d
// At the start of each line, a "-" prefix indicates an element removed from x,
Packit 63bb0d
// a "+" prefix to indicates an element added to y, and the lack of a prefix
Packit 63bb0d
// indicates an element common to both x and y. If possible, the output
Packit 63bb0d
// uses fmt.Stringer.String or error.Error methods to produce more humanly
Packit 63bb0d
// readable outputs. In such cases, the string is prefixed with either an
Packit 63bb0d
// 's' or 'e' character, respectively, to indicate that the method was called.
Packit 63bb0d
//
Packit 63bb0d
// Do not depend on this output being stable. If you need the ability to
Packit 63bb0d
// programmatically interpret the difference, consider using a custom Reporter.
Packit 63bb0d
func Diff(x, y interface{}, opts ...Option) string {
Packit 63bb0d
	r := new(defaultReporter)
Packit 63bb0d
	eq := Equal(x, y, Options(opts), Reporter(r))
Packit 63bb0d
	d := r.String()
Packit 63bb0d
	if (d == "") != eq {
Packit 63bb0d
		panic("inconsistent difference and equality results")
Packit 63bb0d
	}
Packit 63bb0d
	return d
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
type state struct {
Packit 63bb0d
	// These fields represent the "comparison state".
Packit 63bb0d
	// Calling statelessCompare must not result in observable changes to these.
Packit 63bb0d
	result    diff.Result // The current result of comparison
Packit 63bb0d
	curPath   Path        // The current path in the value tree
Packit 63bb0d
	reporters []reporter  // Optional reporters
Packit 63bb0d
Packit 63bb0d
	// recChecker checks for infinite cycles applying the same set of
Packit 63bb0d
	// transformers upon the output of itself.
Packit 63bb0d
	recChecker recChecker
Packit 63bb0d
Packit 63bb0d
	// dynChecker triggers pseudo-random checks for option correctness.
Packit 63bb0d
	// It is safe for statelessCompare to mutate this value.
Packit 63bb0d
	dynChecker dynChecker
Packit 63bb0d
Packit 63bb0d
	// These fields, once set by processOption, will not change.
Packit 63bb0d
	exporters map[reflect.Type]bool // Set of structs with unexported field visibility
Packit 63bb0d
	opts      Options               // List of all fundamental and filter options
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func newState(opts []Option) *state {
Packit 63bb0d
	// Always ensure a validator option exists to validate the inputs.
Packit 63bb0d
	s := &state{opts: Options{validator{}}}
Packit 63bb0d
	s.processOption(Options(opts))
Packit 63bb0d
	return s
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) processOption(opt Option) {
Packit 63bb0d
	switch opt := opt.(type) {
Packit 63bb0d
	case nil:
Packit 63bb0d
	case Options:
Packit 63bb0d
		for _, o := range opt {
Packit 63bb0d
			s.processOption(o)
Packit 63bb0d
		}
Packit 63bb0d
	case coreOption:
Packit 63bb0d
		type filtered interface {
Packit 63bb0d
			isFiltered() bool
Packit 63bb0d
		}
Packit 63bb0d
		if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() {
Packit 63bb0d
			panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt))
Packit 63bb0d
		}
Packit 63bb0d
		s.opts = append(s.opts, opt)
Packit 63bb0d
	case visibleStructs:
Packit 63bb0d
		if s.exporters == nil {
Packit 63bb0d
			s.exporters = make(map[reflect.Type]bool)
Packit 63bb0d
		}
Packit 63bb0d
		for t := range opt {
Packit 63bb0d
			s.exporters[t] = true
Packit 63bb0d
		}
Packit 63bb0d
	case reporter:
Packit 63bb0d
		s.reporters = append(s.reporters, opt)
Packit 63bb0d
	default:
Packit 63bb0d
		panic(fmt.Sprintf("unknown option %T", opt))
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// statelessCompare compares two values and returns the result.
Packit 63bb0d
// This function is stateless in that it does not alter the current result,
Packit 63bb0d
// or output to any registered reporters.
Packit 63bb0d
func (s *state) statelessCompare(step PathStep) diff.Result {
Packit 63bb0d
	// We do not save and restore the curPath because all of the compareX
Packit 63bb0d
	// methods should properly push and pop from the path.
Packit 63bb0d
	// It is an implementation bug if the contents of curPath differs from
Packit 63bb0d
	// when calling this function to when returning from it.
Packit 63bb0d
Packit 63bb0d
	oldResult, oldReporters := s.result, s.reporters
Packit 63bb0d
	s.result = diff.Result{} // Reset result
Packit 63bb0d
	s.reporters = nil        // Remove reporters to avoid spurious printouts
Packit 63bb0d
	s.compareAny(step)
Packit 63bb0d
	res := s.result
Packit 63bb0d
	s.result, s.reporters = oldResult, oldReporters
Packit 63bb0d
	return res
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) compareAny(step PathStep) {
Packit 63bb0d
	// Update the path stack.
Packit 63bb0d
	s.curPath.push(step)
Packit 63bb0d
	defer s.curPath.pop()
Packit 63bb0d
	for _, r := range s.reporters {
Packit 63bb0d
		r.PushStep(step)
Packit 63bb0d
		defer r.PopStep()
Packit 63bb0d
	}
Packit 63bb0d
	s.recChecker.Check(s.curPath)
Packit 63bb0d
Packit 63bb0d
	// Obtain the current type and values.
Packit 63bb0d
	t := step.Type()
Packit 63bb0d
	vx, vy := step.Values()
Packit 63bb0d
Packit 63bb0d
	// Rule 1: Check whether an option applies on this node in the value tree.
Packit 63bb0d
	if s.tryOptions(t, vx, vy) {
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Rule 2: Check whether the type has a valid Equal method.
Packit 63bb0d
	if s.tryMethod(t, vx, vy) {
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Rule 3: Compare based on the underlying kind.
Packit 63bb0d
	switch t.Kind() {
Packit 63bb0d
	case reflect.Bool:
Packit 63bb0d
		s.report(vx.Bool() == vy.Bool(), 0)
Packit 63bb0d
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Packit 63bb0d
		s.report(vx.Int() == vy.Int(), 0)
Packit 63bb0d
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
Packit 63bb0d
		s.report(vx.Uint() == vy.Uint(), 0)
Packit 63bb0d
	case reflect.Float32, reflect.Float64:
Packit 63bb0d
		s.report(vx.Float() == vy.Float(), 0)
Packit 63bb0d
	case reflect.Complex64, reflect.Complex128:
Packit 63bb0d
		s.report(vx.Complex() == vy.Complex(), 0)
Packit 63bb0d
	case reflect.String:
Packit 63bb0d
		s.report(vx.String() == vy.String(), 0)
Packit 63bb0d
	case reflect.Chan, reflect.UnsafePointer:
Packit 63bb0d
		s.report(vx.Pointer() == vy.Pointer(), 0)
Packit 63bb0d
	case reflect.Func:
Packit 63bb0d
		s.report(vx.IsNil() && vy.IsNil(), 0)
Packit 63bb0d
	case reflect.Struct:
Packit 63bb0d
		s.compareStruct(t, vx, vy)
Packit 63bb0d
	case reflect.Slice, reflect.Array:
Packit 63bb0d
		s.compareSlice(t, vx, vy)
Packit 63bb0d
	case reflect.Map:
Packit 63bb0d
		s.compareMap(t, vx, vy)
Packit 63bb0d
	case reflect.Ptr:
Packit 63bb0d
		s.comparePtr(t, vx, vy)
Packit 63bb0d
	case reflect.Interface:
Packit 63bb0d
		s.compareInterface(t, vx, vy)
Packit 63bb0d
	default:
Packit 63bb0d
		panic(fmt.Sprintf("%v kind not handled", t.Kind()))
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool {
Packit 63bb0d
	// Evaluate all filters and apply the remaining options.
Packit 63bb0d
	if opt := s.opts.filter(s, t, vx, vy); opt != nil {
Packit 63bb0d
		opt.apply(s, vx, vy)
Packit 63bb0d
		return true
Packit 63bb0d
	}
Packit 63bb0d
	return false
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool {
Packit 63bb0d
	// Check if this type even has an Equal method.
Packit 63bb0d
	m, ok := t.MethodByName("Equal")
Packit 63bb0d
	if !ok || !function.IsType(m.Type, function.EqualAssignable) {
Packit 63bb0d
		return false
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	eq := s.callTTBFunc(m.Func, vx, vy)
Packit 63bb0d
	s.report(eq, reportByMethod)
Packit 63bb0d
	return true
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value {
Packit 63bb0d
	v = sanitizeValue(v, f.Type().In(0))
Packit 63bb0d
	if !s.dynChecker.Next() {
Packit 63bb0d
		return f.Call([]reflect.Value{v})[0]
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Run the function twice and ensure that we get the same results back.
Packit 63bb0d
	// We run in goroutines so that the race detector (if enabled) can detect
Packit 63bb0d
	// unsafe mutations to the input.
Packit 63bb0d
	c := make(chan reflect.Value)
Packit 63bb0d
	go detectRaces(c, f, v)
Packit 63bb0d
	got := <-c
Packit 63bb0d
	want := f.Call([]reflect.Value{v})[0]
Packit 63bb0d
	if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {
Packit 63bb0d
		// To avoid false-positives with non-reflexive equality operations,
Packit 63bb0d
		// we sanity check whether a value is equal to itself.
Packit 63bb0d
		if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {
Packit 63bb0d
			return want
Packit 63bb0d
		}
Packit 63bb0d
		panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))
Packit 63bb0d
	}
Packit 63bb0d
	return want
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
Packit 63bb0d
	x = sanitizeValue(x, f.Type().In(0))
Packit 63bb0d
	y = sanitizeValue(y, f.Type().In(1))
Packit 63bb0d
	if !s.dynChecker.Next() {
Packit 63bb0d
		return f.Call([]reflect.Value{x, y})[0].Bool()
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Swapping the input arguments is sufficient to check that
Packit 63bb0d
	// f is symmetric and deterministic.
Packit 63bb0d
	// We run in goroutines so that the race detector (if enabled) can detect
Packit 63bb0d
	// unsafe mutations to the input.
Packit 63bb0d
	c := make(chan reflect.Value)
Packit 63bb0d
	go detectRaces(c, f, y, x)
Packit 63bb0d
	got := <-c
Packit 63bb0d
	want := f.Call([]reflect.Value{x, y})[0].Bool()
Packit 63bb0d
	if !got.IsValid() || got.Bool() != want {
Packit 63bb0d
		panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))
Packit 63bb0d
	}
Packit 63bb0d
	return want
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
Packit 63bb0d
	var ret reflect.Value
Packit 63bb0d
	defer func() {
Packit 63bb0d
		recover() // Ignore panics, let the other call to f panic instead
Packit 63bb0d
		c <- ret
Packit 63bb0d
	}()
Packit 63bb0d
	ret = f.Call(vs)[0]
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// sanitizeValue converts nil interfaces of type T to those of type R,
Packit 63bb0d
// assuming that T is assignable to R.
Packit 63bb0d
// Otherwise, it returns the input value as is.
Packit 63bb0d
func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
Packit 63bb0d
	// TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143).
Packit 63bb0d
	if !flags.AtLeastGo110 {
Packit 63bb0d
		if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
Packit 63bb0d
			return reflect.New(t).Elem()
Packit 63bb0d
		}
Packit 63bb0d
	}
Packit 63bb0d
	return v
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {
Packit 63bb0d
	var vax, vay reflect.Value // Addressable versions of vx and vy
Packit 63bb0d
Packit 63bb0d
	step := StructField{&structField{}}
Packit 63bb0d
	for i := 0; i < t.NumField(); i++ {
Packit 63bb0d
		step.typ = t.Field(i).Type
Packit 63bb0d
		step.vx = vx.Field(i)
Packit 63bb0d
		step.vy = vy.Field(i)
Packit 63bb0d
		step.name = t.Field(i).Name
Packit 63bb0d
		step.idx = i
Packit 63bb0d
		step.unexported = !isExported(step.name)
Packit 63bb0d
		if step.unexported {
Packit 63bb0d
			if step.name == "_" {
Packit 63bb0d
				continue
Packit 63bb0d
			}
Packit 63bb0d
			// Defer checking of unexported fields until later to give an
Packit 63bb0d
			// Ignore a chance to ignore the field.
Packit 63bb0d
			if !vax.IsValid() || !vay.IsValid() {
Packit 63bb0d
				// For retrieveUnexportedField to work, the parent struct must
Packit 63bb0d
				// be addressable. Create a new copy of the values if
Packit 63bb0d
				// necessary to make them addressable.
Packit 63bb0d
				vax = makeAddressable(vx)
Packit 63bb0d
				vay = makeAddressable(vy)
Packit 63bb0d
			}
Packit 63bb0d
			step.mayForce = s.exporters[t]
Packit 63bb0d
			step.pvx = vax
Packit 63bb0d
			step.pvy = vay
Packit 63bb0d
			step.field = t.Field(i)
Packit 63bb0d
		}
Packit 63bb0d
		s.compareAny(step)
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {
Packit 63bb0d
	isSlice := t.Kind() == reflect.Slice
Packit 63bb0d
	if isSlice && (vx.IsNil() || vy.IsNil()) {
Packit 63bb0d
		s.report(vx.IsNil() && vy.IsNil(), 0)
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// TODO: Support cyclic data structures.
Packit 63bb0d
Packit 63bb0d
	step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}}}
Packit 63bb0d
	withIndexes := func(ix, iy int) SliceIndex {
Packit 63bb0d
		if ix >= 0 {
Packit 63bb0d
			step.vx, step.xkey = vx.Index(ix), ix
Packit 63bb0d
		} else {
Packit 63bb0d
			step.vx, step.xkey = reflect.Value{}, -1
Packit 63bb0d
		}
Packit 63bb0d
		if iy >= 0 {
Packit 63bb0d
			step.vy, step.ykey = vy.Index(iy), iy
Packit 63bb0d
		} else {
Packit 63bb0d
			step.vy, step.ykey = reflect.Value{}, -1
Packit 63bb0d
		}
Packit 63bb0d
		return step
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Ignore options are able to ignore missing elements in a slice.
Packit 63bb0d
	// However, detecting these reliably requires an optimal differencing
Packit 63bb0d
	// algorithm, for which diff.Difference is not.
Packit 63bb0d
	//
Packit 63bb0d
	// Instead, we first iterate through both slices to detect which elements
Packit 63bb0d
	// would be ignored if standing alone. The index of non-discarded elements
Packit 63bb0d
	// are stored in a separate slice, which diffing is then performed on.
Packit 63bb0d
	var indexesX, indexesY []int
Packit 63bb0d
	var ignoredX, ignoredY []bool
Packit 63bb0d
	for ix := 0; ix < vx.Len(); ix++ {
Packit 63bb0d
		ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0
Packit 63bb0d
		if !ignored {
Packit 63bb0d
			indexesX = append(indexesX, ix)
Packit 63bb0d
		}
Packit 63bb0d
		ignoredX = append(ignoredX, ignored)
Packit 63bb0d
	}
Packit 63bb0d
	for iy := 0; iy < vy.Len(); iy++ {
Packit 63bb0d
		ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0
Packit 63bb0d
		if !ignored {
Packit 63bb0d
			indexesY = append(indexesY, iy)
Packit 63bb0d
		}
Packit 63bb0d
		ignoredY = append(ignoredY, ignored)
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// Compute an edit-script for slices vx and vy (excluding ignored elements).
Packit 63bb0d
	edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {
Packit 63bb0d
		return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))
Packit 63bb0d
	})
Packit 63bb0d
Packit 63bb0d
	// Replay the ignore-scripts and the edit-script.
Packit 63bb0d
	var ix, iy int
Packit 63bb0d
	for ix < vx.Len() || iy < vy.Len() {
Packit 63bb0d
		var e diff.EditType
Packit 63bb0d
		switch {
Packit 63bb0d
		case ix < len(ignoredX) && ignoredX[ix]:
Packit 63bb0d
			e = diff.UniqueX
Packit 63bb0d
		case iy < len(ignoredY) && ignoredY[iy]:
Packit 63bb0d
			e = diff.UniqueY
Packit 63bb0d
		default:
Packit 63bb0d
			e, edits = edits[0], edits[1:]
Packit 63bb0d
		}
Packit 63bb0d
		switch e {
Packit 63bb0d
		case diff.UniqueX:
Packit 63bb0d
			s.compareAny(withIndexes(ix, -1))
Packit 63bb0d
			ix++
Packit 63bb0d
		case diff.UniqueY:
Packit 63bb0d
			s.compareAny(withIndexes(-1, iy))
Packit 63bb0d
			iy++
Packit 63bb0d
		default:
Packit 63bb0d
			s.compareAny(withIndexes(ix, iy))
Packit 63bb0d
			ix++
Packit 63bb0d
			iy++
Packit 63bb0d
		}
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {
Packit 63bb0d
	if vx.IsNil() || vy.IsNil() {
Packit 63bb0d
		s.report(vx.IsNil() && vy.IsNil(), 0)
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// TODO: Support cyclic data structures.
Packit 63bb0d
Packit 63bb0d
	// We combine and sort the two map keys so that we can perform the
Packit 63bb0d
	// comparisons in a deterministic order.
Packit 63bb0d
	step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}
Packit 63bb0d
	for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {
Packit 63bb0d
		step.vx = vx.MapIndex(k)
Packit 63bb0d
		step.vy = vy.MapIndex(k)
Packit 63bb0d
		step.key = k
Packit 63bb0d
		if !step.vx.IsValid() && !step.vy.IsValid() {
Packit 63bb0d
			// It is possible for both vx and vy to be invalid if the
Packit 63bb0d
			// key contained a NaN value in it.
Packit 63bb0d
			//
Packit 63bb0d
			// Even with the ability to retrieve NaN keys in Go 1.12,
Packit 63bb0d
			// there still isn't a sensible way to compare the values since
Packit 63bb0d
			// a NaN key may map to multiple unordered values.
Packit 63bb0d
			// The most reasonable way to compare NaNs would be to compare the
Packit 63bb0d
			// set of values. However, this is impossible to do efficiently
Packit 63bb0d
			// since set equality is provably an O(n^2) operation given only
Packit 63bb0d
			// an Equal function. If we had a Less function or Hash function,
Packit 63bb0d
			// this could be done in O(n*log(n)) or O(n), respectively.
Packit 63bb0d
			//
Packit 63bb0d
			// Rather than adding complex logic to deal with NaNs, make it
Packit 63bb0d
			// the user's responsibility to compare such obscure maps.
Packit 63bb0d
			const help = "consider providing a Comparer to compare the map"
Packit 63bb0d
			panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))
Packit 63bb0d
		}
Packit 63bb0d
		s.compareAny(step)
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
Packit 63bb0d
	if vx.IsNil() || vy.IsNil() {
Packit 63bb0d
		s.report(vx.IsNil() && vy.IsNil(), 0)
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
Packit 63bb0d
	// TODO: Support cyclic data structures.
Packit 63bb0d
Packit 63bb0d
	vx, vy = vx.Elem(), vy.Elem()
Packit 63bb0d
	s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {
Packit 63bb0d
	if vx.IsNil() || vy.IsNil() {
Packit 63bb0d
		s.report(vx.IsNil() && vy.IsNil(), 0)
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
	vx, vy = vx.Elem(), vy.Elem()
Packit 63bb0d
	if vx.Type() != vy.Type() {
Packit 63bb0d
		s.report(false, 0)
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
	s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
func (s *state) report(eq bool, rf resultFlags) {
Packit 63bb0d
	if rf&reportByIgnore == 0 {
Packit 63bb0d
		if eq {
Packit 63bb0d
			s.result.NumSame++
Packit 63bb0d
			rf |= reportEqual
Packit 63bb0d
		} else {
Packit 63bb0d
			s.result.NumDiff++
Packit 63bb0d
			rf |= reportUnequal
Packit 63bb0d
		}
Packit 63bb0d
	}
Packit 63bb0d
	for _, r := range s.reporters {
Packit 63bb0d
		r.Report(Result{flags: rf})
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// recChecker tracks the state needed to periodically perform checks that
Packit 63bb0d
// user provided transformers are not stuck in an infinitely recursive cycle.
Packit 63bb0d
type recChecker struct{ next int }
Packit 63bb0d
Packit 63bb0d
// Check scans the Path for any recursive transformers and panics when any
Packit 63bb0d
// recursive transformers are detected. Note that the presence of a
Packit 63bb0d
// recursive Transformer does not necessarily imply an infinite cycle.
Packit 63bb0d
// As such, this check only activates after some minimal number of path steps.
Packit 63bb0d
func (rc *recChecker) Check(p Path) {
Packit 63bb0d
	const minLen = 1 << 16
Packit 63bb0d
	if rc.next == 0 {
Packit 63bb0d
		rc.next = minLen
Packit 63bb0d
	}
Packit 63bb0d
	if len(p) < rc.next {
Packit 63bb0d
		return
Packit 63bb0d
	}
Packit 63bb0d
	rc.next <<= 1
Packit 63bb0d
Packit 63bb0d
	// Check whether the same transformer has appeared at least twice.
Packit 63bb0d
	var ss []string
Packit 63bb0d
	m := map[Option]int{}
Packit 63bb0d
	for _, ps := range p {
Packit 63bb0d
		if t, ok := ps.(Transform); ok {
Packit 63bb0d
			t := t.Option()
Packit 63bb0d
			if m[t] == 1 { // Transformer was used exactly once before
Packit 63bb0d
				tf := t.(*transformer).fnc.Type()
Packit 63bb0d
				ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
Packit 63bb0d
			}
Packit 63bb0d
			m[t]++
Packit 63bb0d
		}
Packit 63bb0d
	}
Packit 63bb0d
	if len(ss) > 0 {
Packit 63bb0d
		const warning = "recursive set of Transformers detected"
Packit 63bb0d
		const help = "consider using cmpopts.AcyclicTransformer"
Packit 63bb0d
		set := strings.Join(ss, "\n\t")
Packit 63bb0d
		panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
Packit 63bb0d
	}
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// dynChecker tracks the state needed to periodically perform checks that
Packit 63bb0d
// user provided functions are symmetric and deterministic.
Packit 63bb0d
// The zero value is safe for immediate use.
Packit 63bb0d
type dynChecker struct{ curr, next int }
Packit 63bb0d
Packit 63bb0d
// Next increments the state and reports whether a check should be performed.
Packit 63bb0d
//
Packit 63bb0d
// Checks occur every Nth function call, where N is a triangular number:
Packit 63bb0d
//	0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...
Packit 63bb0d
// See https://en.wikipedia.org/wiki/Triangular_number
Packit 63bb0d
//
Packit 63bb0d
// This sequence ensures that the cost of checks drops significantly as
Packit 63bb0d
// the number of functions calls grows larger.
Packit 63bb0d
func (dc *dynChecker) Next() bool {
Packit 63bb0d
	ok := dc.curr == dc.next
Packit 63bb0d
	if ok {
Packit 63bb0d
		dc.curr = 0
Packit 63bb0d
		dc.next++
Packit 63bb0d
	}
Packit 63bb0d
	dc.curr++
Packit 63bb0d
	return ok
Packit 63bb0d
}
Packit 63bb0d
Packit 63bb0d
// makeAddressable returns a value that is always addressable.
Packit 63bb0d
// It returns the input verbatim if it is already addressable,
Packit 63bb0d
// otherwise it creates a new value and returns an addressable copy.
Packit 63bb0d
func makeAddressable(v reflect.Value) reflect.Value {
Packit 63bb0d
	if v.CanAddr() {
Packit 63bb0d
		return v
Packit 63bb0d
	}
Packit 63bb0d
	vc := reflect.New(v.Type()).Elem()
Packit 63bb0d
	vc.Set(v)
Packit 63bb0d
	return vc
Packit 63bb0d
}