| 1 |
// Copyright (c) 2019-2025, 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 tdutil |
| 8 |
|
| 9 |
import ( |
| 10 |
"reflect" |
| 11 |
"sort" |
| 12 |
|
| 13 |
tdsort "github.com/maxatome/go-testdeep/internal/sort" |
| 14 |
) |
| 15 |
|
| 16 |
// SortableValues is used to allow the sorting of a [][reflect.Value] |
| 17 |
// slice. It is used with the standard sort package: |
| 18 |
// |
| 19 |
// vals := []reflect.Value{a, b, c, d} |
| 20 |
// sort.Sort(SortableValues(vals)) |
| 21 |
// // vals contents now sorted |
| 22 |
// |
| 23 |
// Replace [sort.Sort] by [sort.Stable] for a stable sort. See [sort] |
| 24 |
// documentation. |
| 25 |
// |
| 26 |
// Sorting rules are as follows: |
| 27 |
// - invalid value is always lower |
| 28 |
// - nil is always lower |
| 29 |
// - different types are sorted by their name |
| 30 |
// - if method TYPE.Compare(TYPE) int exits, calls it |
| 31 |
// - false is lesser than true |
| 32 |
// - float and int numbers are sorted by their value, NaN is always lower |
| 33 |
// - complex numbers are sorted by their real, then by their imaginary parts |
| 34 |
// - strings are sorted by their value |
| 35 |
// - map: shorter length is lesser, then sorted by address |
| 36 |
// - functions, channels and unsafe pointer are sorted by their address |
| 37 |
// - struct: comparison is spread to each field |
| 38 |
// - pointer: comparison is spread to the pointed value |
| 39 |
// - arrays: comparison is spread to each item |
| 40 |
// - slice: comparison is spread to each item, then shorter length is lesser |
| 41 |
// - interface: comparison is spread to the value |
| 42 |
// |
| 43 |
// Cyclic references are correctly handled. |
| 44 |
// |
| 45 |
// See also [CmpValuesFunc]. |
| 46 |
func SortableValues(s []reflect.Value) sort.Interface { |
| 47 |
return tdsort.Values(s) |
| 48 |
} |
| 49 |
|
| 50 |
// CmpValuesFunc returns a function able to compare 2 [reflect.Value] values. |
| 51 |
// |
| 52 |
// The sorting rules are listed in [SortableValues] documentation. |
| 53 |
// |
| 54 |
// values := s := []reflect.Value{ |
| 55 |
// reflect.ValueOf(4), |
| 56 |
// reflect.ValueOf(3), |
| 57 |
// reflect.ValueOf(1), |
| 58 |
// } |
| 59 |
// slices.SortFunc(s, tdutil.CmpValuesFunc()) |
| 60 |
// |
| 61 |
// Cyclic references are correctly handled. |
| 62 |
// |
| 63 |
// See also [SortableValues]. |
| 64 |
func CmpValuesFunc() func(a, b reflect.Value) int { |
| 65 |
return tdsort.Func() |
| 66 |
} |