Debian Codegraph @

common/hreflect/compare_test.go

raw
1 // Copyright 2026 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hreflect
15
16 import (
17 "math"
18 "reflect"
19 "testing"
20
21 qt "github.com/frankban/quicktest"
22 )
23
24 func TestCompareNumbers(t *testing.T) {
25 t.Parallel()
26 c := qt.New(t)
27
28 for _, test := range []struct {
29 a, b any
30 expect int
31 }{
32 {1, 1, 0},
33 {1, 2, -1},
34 {int8(-1), int64(-2), 1},
35 {uint8(1), uint64(1), 0},
36 {uint64(math.MaxUint64), uint8(1), 1},
37 {-1, uint64(math.MaxUint64), -1},
38 {uint64(math.MaxUint64), -1, 1},
39 {int64(math.MaxInt64), uint64(math.MaxInt64), 0},
40 {int64(math.MaxInt64), uint64(1 << 63), -1},
41 {1, 1.0, 0},
42 {1.0, 1, 0},
43 {1, 1.5, -1},
44 {2, 1.5, 1},
45 {-1, -1.5, 1},
46 {-2, -1.5, -1},
47 {1.5, 1, 1},
48 {-1.5, -1, -1},
49 {int64(1<<53 + 1), float64(1 << 53), 1},
50 {float64(1 << 53), int64(1<<53 + 1), -1},
51 {int64(1 << 53), float64(1 << 53), 0},
52 {int64(math.MaxInt64), float64(1 << 63), -1},
53 {int64(math.MinInt64), float64(-(1 << 63)), 0},
54 {int64(math.MinInt64), -1e300, 1},
55 {uint64(math.MaxUint64), float64(1 << 64), -1},
56 {uint64(0), -0.5, 1},
57 {uint64(0), math.Copysign(0, -1), 0},
58 {uint64(1<<53 + 1), float64(1 << 53), 1},
59 {float32(1.5), 1.5, 0},
60 {float32(1.1), 1.1, 1},
61 {math.Inf(1), int64(math.MaxInt64), 1},
62 {math.Inf(-1), uint64(0), -1},
63 } {
64 got, ok := CompareNumbers(reflect.ValueOf(test.a), reflect.ValueOf(test.b))
65 c.Assert(ok, qt.IsTrue, qt.Commentf("%v vs %v", test.a, test.b))
66 c.Assert(got, qt.Equals, test.expect, qt.Commentf("%v vs %v", test.a, test.b))
67 }
68
69 for _, test := range [][2]any{
70 {math.NaN(), 1},
71 {1, math.NaN()},
72 {math.NaN(), math.NaN()},
73 {"1", 1},
74 {1, "1"},
75 {true, 1},
76 {nil, 1},
77 } {
78 _, ok := CompareNumbers(reflect.ValueOf(test[0]), reflect.ValueOf(test[1]))
79 c.Assert(ok, qt.IsFalse, qt.Commentf("%v vs %v", test[0], test[1]))
80 }
81 }