Debian Codegraph @

internal/sort/sort.go

raw
1 // Copyright (c) 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 sort
8
9 import (
10 "reflect"
11 "sort"
12
13 "github.com/maxatome/go-testdeep/internal/compare"
14 "github.com/maxatome/go-testdeep/internal/visited"
15 )
16
17 // Values is used to allow the sorting of a [][reflect.Value]
18 // slice. It is used with the standard sort package:
19 //
20 // vals := []reflect.Value{a, b, c, d}
21 // sort.Sort(Values(vals))
22 // // vals contents now sorted
23 //
24 // Replace [sort.Sort] by [sort.Stable] for a stable sort. See [sort]
25 // documentation.
26 //
27 // Sorting rules are as follows:
28 // - invalid value is always lower
29 // - nil is always lower
30 // - different types are sorted by their name
31 // - if method TYPE.Compare(TYPE) int exits, calls it
32 // - false is lesser than true
33 // - float and int numbers are sorted by their value, NaN is always lower
34 // - complex numbers are sorted by their real, then by their imaginary parts
35 // - strings are sorted by their value
36 // - map: shorter length is lesser, then sorted by address
37 // - functions, channels and unsafe pointer are sorted by their address
38 // - struct: comparison is spread to each field
39 // - pointer: comparison is spread to the pointed value
40 // - arrays: comparison is spread to each item
41 // - slice: comparison is spread to each item, then shorter length is lesser
42 // - interface: comparison is spread to the value
43 //
44 // Cyclic references are correctly handled.
45 //
46 // See also [Func].
47 func Values(s []reflect.Value) sort.Interface {
48 r := &rValues{
49 Slice: s,
50 }
51 if len(s) > 1 {
52 r.Visited = visited.NewVisited()
53 }
54 return r
55 }
56
57 type rValues struct {
58 Visited visited.Visited
59 Slice []reflect.Value
60 }
61
62 func (v *rValues) Len() int {
63 return len(v.Slice)
64 }
65
66 func (v *rValues) Less(i, j int) bool {
67 return compare.Compare(v.Visited, v.Slice[i], v.Slice[j]) < 0
68 }
69
70 func (v *rValues) Swap(i, j int) {
71 v.Slice[i], v.Slice[j] = v.Slice[j], v.Slice[i]
72 }
73
74 // Func returns a function able to compare 2 [reflect.Value] values.
75 //
76 // The sorting rules are listed in [Values] documentation.
77 //
78 // Cyclic references are correctly handled.
79 func Func() func(a, b reflect.Value) int {
80 var v visited.Visited
81 return func(a, b reflect.Value) int {
82 return compare.Compare(v, a, b)
83 }
84 }