| 1 |
// Package deepequal provides improved [reflect.DeepEqual]. |
| 2 |
// |
| 3 |
// Differences from [reflect.DeepEqual]: |
| 4 |
// |
| 5 |
// - If compared value implements `.Equal(valueOfSameType) bool` method then |
| 6 |
// it will be called instead of comparing values as is. |
| 7 |
// - If called `Equal` method will panics then whole DeepEqual will panics too. |
| 8 |
// |
| 9 |
// This means you can use this DeepEqual method to correctly compare types |
| 10 |
// like [time.Time] or decimal.Decimal, without taking in account unimportant |
| 11 |
// differences (like time zone or exponent). |
| 12 |
package deepequal |
| 13 |
|
| 14 |
import ( |
| 15 |
"reflect" |
| 16 |
"unsafe" |
| 17 |
) |
| 18 |
|
| 19 |
// Disable check for unexported values. |
| 20 |
func forceExported(v *reflect.Value) (undo func()) { |
| 21 |
ref := (*value)(unsafe.Pointer(v)) //nolint:gosec // Audit. |
| 22 |
flag := ref.flag |
| 23 |
ref.flag &^= flagRO |
| 24 |
return func() { ref.flag = flag } |
| 25 |
} |
| 26 |
|
| 27 |
func valueInterface(v reflect.Value) any { |
| 28 |
undo := forceExported(&v) |
| 29 |
defer undo() |
| 30 |
return v.Interface() |
| 31 |
} |
| 32 |
|
| 33 |
// hasPointers reports whether v's type contains pointers. |
| 34 |
// It's used to detect not-in-heap pointers, which can't be cyclic. |
| 35 |
func hasPointers(v reflect.Value) bool { |
| 36 |
ref := (*value)(unsafe.Pointer(&v)) //nolint:gosec // Audit. |
| 37 |
return ref.typ.Pointers() |
| 38 |
} |
| 39 |
|
| 40 |
func call(v reflect.Value, in []reflect.Value) []reflect.Value { |
| 41 |
undo := forceExported(&v) |
| 42 |
defer undo() |
| 43 |
undoIn := make([]func(), len(in)) |
| 44 |
for i := range in { |
| 45 |
undoIn[i] = forceExported(&in[i]) |
| 46 |
} |
| 47 |
defer func() { |
| 48 |
for _, fn := range undoIn { |
| 49 |
fn() |
| 50 |
} |
| 51 |
}() |
| 52 |
return v.Call(in) |
| 53 |
} |
| 54 |
|
| 55 |
//nolint:gochecknoglobals // Const. |
| 56 |
var boolType = reflect.TypeFor[bool]() |
| 57 |
|
| 58 |
func equalFunc(v reflect.Value) (equal reflect.Value, ok bool) { |
| 59 |
equal = v.MethodByName("Equal") |
| 60 |
if !equal.IsValid() { |
| 61 |
return equal, false |
| 62 |
} |
| 63 |
typ := equal.Type() |
| 64 |
ok = typ.NumIn() == 1 && typ.In(0) == v.Type() && |
| 65 |
typ.NumOut() == 1 && typ.Out(0) == boolType |
| 66 |
return equal, ok |
| 67 |
} |