Debian Codegraph @

common/hreflect/compare.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 "cmp"
18 "math"
19 "reflect"
20 )
21
22 // CompareNumbers compares a and b exactly, without first converting integers to float64.
23 // It returns -1, 0 or 1. ok is false if a or b is not a number or is NaN.
24 func CompareNumbers(a, b reflect.Value) (c int, ok bool) {
25 ak, bk := a.Kind(), b.Kind()
26 switch {
27 case IsInt(ak):
28 switch {
29 case IsInt(bk):
30 return cmp.Compare(a.Int(), b.Int()), true
31 case IsUint(bk):
32 return compareIntUint(a.Int(), b.Uint()), true
33 case IsFloat(bk):
34 return compareIntFloat(a.Int(), b.Float())
35 }
36 case IsUint(ak):
37 switch {
38 case IsInt(bk):
39 return -compareIntUint(b.Int(), a.Uint()), true
40 case IsUint(bk):
41 return cmp.Compare(a.Uint(), b.Uint()), true
42 case IsFloat(bk):
43 return compareUintFloat(a.Uint(), b.Float())
44 }
45 case IsFloat(ak):
46 switch {
47 case IsInt(bk):
48 c, ok := compareIntFloat(b.Int(), a.Float())
49 return -c, ok
50 case IsUint(bk):
51 c, ok := compareUintFloat(b.Uint(), a.Float())
52 return -c, ok
53 case IsFloat(bk):
54 af, bf := a.Float(), b.Float()
55 if math.IsNaN(af) || math.IsNaN(bf) {
56 return 0, false
57 }
58 return cmp.Compare(af, bf), true
59 }
60 }
61 return 0, false
62 }
63
64 func compareIntUint(i int64, u uint64) int {
65 if i < 0 {
66 return -1
67 }
68 return cmp.Compare(uint64(i), u)
69 }
70
71 func compareIntFloat(i int64, f float64) (int, bool) {
72 switch {
73 case math.IsNaN(f):
74 return 0, false
75 case f >= 1<<63:
76 return -1, true
77 case f < -(1 << 63):
78 return 1, true
79 }
80 if c := cmp.Compare(i, int64(f)); c != 0 {
81 return c, true
82 }
83 return cmp.Compare(0, f-math.Trunc(f)), true
84 }
85
86 func compareUintFloat(u uint64, f float64) (int, bool) {
87 switch {
88 case math.IsNaN(f):
89 return 0, false
90 case f >= 1<<64:
91 return -1, true
92 case f < 0:
93 return 1, true
94 }
95 if c := cmp.Compare(u, uint64(f)); c != 0 {
96 return c, true
97 }
98 return cmp.Compare(0, f-math.Trunc(f)), true
99 }