1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 var negzero = math.Copysign(0, -1)
18 var tests = []struct {
31 {math.Inf(1), math.Inf(1), 0},
32 {math.Inf(-1), math.Inf(-1), 0},
33 {math.Inf(-1), 1.0, -1},
34 {1.0, math.Inf(-1), +1},
35 {math.Inf(1), 1.0, +1},
36 {1.0, math.Inf(1), -1},
37 {math.NaN(), math.NaN(), 0},
38 {0.0, math.NaN(), +1},
39 {math.NaN(), 0.0, -1},
40 {math.NaN(), math.Inf(-1), -1},
41 {math.Inf(-1), math.NaN(), +1},
43 {negzero, negzero, 0},
50 func TestLess(t *testing.T) {
51 for _, test := range tests {
53 switch test.x.(type) {
55 b = cmp.Less(test.x.(int), test.y.(int))
57 b = cmp.Less(test.x.(string), test.y.(string))
59 b = cmp.Less(test.x.(float64), test.y.(float64))
61 if b != (test.compare < 0) {
62 t.Errorf("Less(%v, %v) == %t, want %t", test.x, test.y, b, test.compare < 0)
67 func TestCompare(t *testing.T) {
68 for _, test := range tests {
70 switch test.x.(type) {
72 c = cmp.Compare(test.x.(int), test.y.(int))
74 c = cmp.Compare(test.x.(string), test.y.(string))
76 c = cmp.Compare(test.x.(float64), test.y.(float64))
78 if c != test.compare {
79 t.Errorf("Compare(%v, %v) == %d, want %d", test.x, test.y, c, test.compare)
84 func TestSort(t *testing.T) {
85 // Test that our comparison function is consistent with
87 input := []float64{1.0, 0.0, negzero, math.Inf(1), math.Inf(-1), math.NaN()}
89 for i := 0; i < len(input)-1; i++ {
90 if cmp.Less(input[i+1], input[i]) {
91 t.Errorf("Less sort mismatch at %d in %v", i, input)
93 if cmp.Compare(input[i], input[i+1]) > 0 {
94 t.Errorf("Compare sort mismatch at %d in %v", i, input)
99 func TestOr(t *testing.T) {
112 for _, tc := range cases {
113 if got := cmp.Or(tc.in...); got != tc.want {
114 t.Errorf("cmp.Or(%v) = %v; want %v", tc.in, got, tc.want)
120 // Suppose we have some user input
121 // that may or may not be an empty string
123 userInput2 := "some text"
125 fmt.Println(cmp.Or(userInput1, "default"))
126 fmt.Println(cmp.Or(userInput2, "default"))
127 fmt.Println(cmp.Or(userInput1, userInput2, "default"))
134 func ExampleOr_sort() {
141 {"foo", "alice", 1.00},
142 {"bar", "bob", 3.00},
143 {"baz", "carol", 4.00},
144 {"foo", "alice", 2.00},
145 {"bar", "carol", 1.00},
146 {"foo", "bob", 4.00},
148 // Sort by customer first, product second, and last by higher price
149 slices.SortFunc(orders, func(a, b Order) int {
151 cmp.Compare(a.Customer, b.Customer),
152 cmp.Compare(a.Product, b.Product),
153 cmp.Compare(b.Price, a.Price),
156 for _, order := range orders {
157 fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)