| 1 |
// Copyright (c) 2021-2022, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package types |
| 8 |
|
| 9 |
import ( |
| 10 |
"reflect" |
| 11 |
|
| 12 |
"github.com/maxatome/go-testdeep/internal/dark" |
| 13 |
) |
| 14 |
|
| 15 |
// NewOrder returns a function able to compare 2 non-nil values of type t. |
| 16 |
// It returns nil if the type t is not comparable. |
| 17 |
func NewOrder(t reflect.Type) func(a, b reflect.Value) int { |
| 18 |
// Compare(T) int |
| 19 |
if m, ok := cmpMethod("Compare", t, Int); ok { |
| 20 |
return func(va, vb reflect.Value) int { |
| 21 |
// use dark.MustGetInterface() to bypass possible private fields |
| 22 |
ret := m.Call([]reflect.Value{ |
| 23 |
reflect.ValueOf(dark.MustGetInterface(va)), |
| 24 |
reflect.ValueOf(dark.MustGetInterface(vb)), |
| 25 |
}) |
| 26 |
return int(ret[0].Int()) |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
// Less(T) bool |
| 31 |
if m, ok := cmpMethod("Less", t, Bool); ok { |
| 32 |
return func(va, vb reflect.Value) int { |
| 33 |
// use dark.MustGetInterface() to bypass possible private fields |
| 34 |
va = reflect.ValueOf(dark.MustGetInterface(va)) |
| 35 |
vb = reflect.ValueOf(dark.MustGetInterface(vb)) |
| 36 |
ret := m.Call([]reflect.Value{va, vb}) |
| 37 |
if ret[0].Bool() { // a < b |
| 38 |
return -1 |
| 39 |
} |
| 40 |
ret = m.Call([]reflect.Value{vb, va}) |
| 41 |
if ret[0].Bool() { // b < a |
| 42 |
return 1 |
| 43 |
} |
| 44 |
return 0 |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return nil |
| 49 |
} |
| 50 |
|
| 51 |
func cmpMethod(name string, in, out reflect.Type) (reflect.Value, bool) { |
| 52 |
if equal, ok := in.MethodByName(name); ok { |
| 53 |
ft := equal.Type |
| 54 |
if !ft.IsVariadic() && |
| 55 |
ft.NumIn() == 2 && |
| 56 |
ft.NumOut() == 1 && |
| 57 |
ft.In(0) == in && |
| 58 |
ft.In(1) == in && |
| 59 |
ft.Out(0) == out { |
| 60 |
return equal.Func, true |
| 61 |
} |
| 62 |
} |
| 63 |
return reflect.Value{}, false |
| 64 |
} |