Debian Codegraph @

tpl/compare/compare.go

raw
1 // Copyright 2017 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 compare provides template functions for comparing values.
15 package compare
16
17 import (
18 "fmt"
19 "math"
20 "reflect"
21 "strconv"
22 "strings"
23 "time"
24
25 "github.com/gohugoio/hugo/compare"
26 "github.com/gohugoio/hugo/langs"
27
28 "github.com/gohugoio/hugo/common/hreflect"
29 "github.com/gohugoio/hugo/common/htime"
30 "github.com/gohugoio/hugo/common/types"
31 )
32
33 // New returns a new instance of the compare-namespaced template functions.
34 func New(loc *time.Location, caseInsensitive bool) *Namespace {
35 return &Namespace{loc: loc, caseInsensitive: caseInsensitive}
36 }
37
38 // Namespace provides template functions for the "compare" namespace.
39 type Namespace struct {
40 loc *time.Location
41 // Enable to do case insensitive string compares.
42 caseInsensitive bool
43 }
44
45 // Default checks whether a givenv is set and returns the default value defaultv if it
46 // is not. "Set" in this context means non-zero for numeric types and times;
47 // non-zero length for strings, arrays, slices, and maps;
48 // any boolean or struct value; or non-nil for any other types.
49 func (*Namespace) Default(defaultv any, givenv ...any) (any, error) {
50 // given is variadic because the following construct will not pass a piped
51 // argument when the key is missing: {{ index . "key" | default "foo" }}
52 // The Go template will complain that we got 1 argument when we expected 2.
53
54 if len(givenv) == 0 {
55 return defaultv, nil
56 }
57 if len(givenv) != 1 {
58 return nil, fmt.Errorf("wrong number of args for default: want 2 got %d", len(givenv)+1)
59 }
60
61 g := reflect.ValueOf(givenv[0])
62 if !g.IsValid() {
63 return defaultv, nil
64 }
65
66 set := false
67
68 switch g.Kind() {
69 case reflect.Bool:
70 set = true
71 case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
72 set = g.Len() != 0
73 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
74 set = g.Int() != 0
75 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
76 set = g.Uint() != 0
77 case reflect.Float32, reflect.Float64:
78 set = g.Float() != 0
79 case reflect.Complex64, reflect.Complex128:
80 set = g.Complex() != 0
81 case reflect.Struct:
82 switch actual := givenv[0].(type) {
83 case time.Time:
84 set = !actual.IsZero()
85 default:
86 set = true
87 }
88 default:
89 set = !g.IsNil()
90 }
91
92 if set {
93 return givenv[0], nil
94 }
95
96 return defaultv, nil
97 }
98
99 // Eq returns the boolean truth of arg1 == arg2 || arg1 == arg3 || arg1 == arg4.
100 // Numbers are compared by value regardless of type, so e.g. 1 and 1.0 are considered equal.
101 func (n *Namespace) Eq(first any, others ...any) bool {
102 if n.caseInsensitive {
103 panic("caseInsensitive not implemented for Eq")
104 }
105 n.checkComparisonArgCount(1, others...)
106 normalize := func(v any) any {
107 if types.IsNil(v) {
108 return nil
109 }
110 if at, ok := v.(htime.AsTimeProvider); ok {
111 return at.AsTime(n.loc)
112 }
113 return v
114 }
115
116 normFirst := normalize(first)
117 fv := reflect.ValueOf(normFirst)
118 for _, other := range others {
119 if e, ok := first.(compare.Eqer); ok {
120 if e.Eq(other) {
121 return true
122 }
123 continue
124 }
125
126 if e, ok := other.(compare.Eqer); ok {
127 if e.Eq(first) {
128 return true
129 }
130 continue
131 }
132
133 other = normalize(other)
134 if normFirst == nil || other == nil {
135 if normFirst == other {
136 return true
137 }
138 continue
139 }
140
141 ov := reflect.ValueOf(other)
142
143 if fv.Kind() == reflect.String && ov.Kind() == reflect.String {
144 if fv.String() == ov.String() {
145 return true
146 }
147 continue
148 }
149
150 if c, ok := hreflect.CompareNumbers(fv, ov); ok {
151 if c == 0 {
152 return true
153 }
154 continue
155 }
156
157 if reflect.DeepEqual(normFirst, other) {
158 return true
159 }
160 }
161
162 return false
163 }
164
165 // Ne returns the boolean truth of arg1 != arg2 && arg1 != arg3 && arg1 != arg4.
166 func (n *Namespace) Ne(first any, others ...any) bool {
167 n.checkComparisonArgCount(1, others...)
168 for _, other := range others {
169 if n.Eq(first, other) {
170 return false
171 }
172 }
173 return true
174 }
175
176 // Ge returns the boolean truth of arg1 >= arg2 && arg1 >= arg3 && arg1 >= arg4.
177 func (n *Namespace) Ge(first any, others ...any) bool {
178 n.checkComparisonArgCount(1, others...)
179 for _, other := range others {
180 left, right := n.compareGet(first, other)
181 if !(left >= right) {
182 return false
183 }
184 }
185 return true
186 }
187
188 // Gt returns the boolean truth of arg1 > arg2 && arg1 > arg3 && arg1 > arg4.
189 func (n *Namespace) Gt(first any, others ...any) bool {
190 n.checkComparisonArgCount(1, others...)
191 for _, other := range others {
192 left, right := n.compareGet(first, other)
193 if !(left > right) {
194 return false
195 }
196 }
197 return true
198 }
199
200 // Le returns the boolean truth of arg1 <= arg2 && arg1 <= arg3 && arg1 <= arg4.
201 func (n *Namespace) Le(first any, others ...any) bool {
202 n.checkComparisonArgCount(1, others...)
203 for _, other := range others {
204 left, right := n.compareGet(first, other)
205 if !(left <= right) {
206 return false
207 }
208 }
209 return true
210 }
211
212 // LtCollate returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4.
213 // The provided collator will be used for string comparisons.
214 // This is for internal use.
215 func (n *Namespace) LtCollate(collator *langs.Collator, first any, others ...any) bool {
216 n.checkComparisonArgCount(1, others...)
217 for _, other := range others {
218 left, right := n.compareGetWithCollator(collator, first, other)
219 if !(left < right) {
220 return false
221 }
222 }
223 return true
224 }
225
226 // Lt returns the boolean truth of arg1 < arg2 && arg1 < arg3 && arg1 < arg4.
227 func (n *Namespace) Lt(first any, others ...any) bool {
228 return n.LtCollate(nil, first, others...)
229 }
230
231 func (n *Namespace) checkComparisonArgCount(min int, others ...any) bool {
232 if len(others) < min {
233 panic("missing arguments for comparison")
234 }
235 return true
236 }
237
238 // Conditional can be used as a ternary operator.
239 //
240 // It returns v1 if cond is true, else v2.
241 func (n *Namespace) Conditional(cond any, v1, v2 any) any {
242 if hreflect.IsTruthful(cond) {
243 return v1
244 }
245 return v2
246 }
247
248 func (ns *Namespace) compareGet(a any, b any) (float64, float64) {
249 return ns.compareGetWithCollator(nil, a, b)
250 }
251
252 // toLeftRight maps a three-way comparison result to the (left, right)
253 // pair convention used by compareGet.
254 func toLeftRight(c int) (float64, float64) {
255 switch {
256 case c < 0:
257 return 0, 1
258 case c > 0:
259 return 1, 0
260 }
261 return 0, 0
262 }
263
264 func (ns *Namespace) compareGetWithCollator(collator *langs.Collator, a any, b any) (float64, float64) {
265 if ac, ok := a.(compare.Comparer); ok {
266 return toLeftRight(-ac.Compare(b))
267 }
268
269 if bc, ok := b.(compare.Comparer); ok {
270 return toLeftRight(bc.Compare(a))
271 }
272
273 // Fast path: both values are plain strings.
274 if as, aOk := a.(string); aOk {
275 if bs, bOk := b.(string); bOk {
276 return ns.compareTwoStrings(collator, as, bs)
277 }
278 }
279
280 av := reflect.ValueOf(a)
281 bv := reflect.ValueOf(b)
282
283 if c, ok := hreflect.CompareNumbers(av, bv); ok {
284 return toLeftRight(c)
285 }
286
287 var left, right float64
288 var leftStr, rightStr *string
289
290 switch av.Kind() {
291 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
292 left = float64(av.Len())
293 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
294 left = float64(av.Int())
295 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
296 left = float64(av.Uint())
297 case reflect.Float32, reflect.Float64:
298 left = av.Float()
299 case reflect.String:
300 var err error
301 left, err = strconv.ParseFloat(av.String(), 64)
302 // Check if float is a special floating value and cast value as string.
303 if math.IsInf(left, 0) || math.IsNaN(left) || err != nil {
304 str := av.String()
305 leftStr = &str
306 }
307 case reflect.Struct:
308 if hreflect.IsTime(av.Type()) {
309 left = float64(ns.toTimeUnix(av))
310 }
311 case reflect.Bool:
312 left = 0
313 if av.Bool() {
314 left = 1
315 }
316 }
317
318 switch bv.Kind() {
319 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
320 right = float64(bv.Len())
321 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
322 right = float64(bv.Int())
323 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
324 right = float64(bv.Uint())
325 case reflect.Float32, reflect.Float64:
326 right = bv.Float()
327 case reflect.String:
328 var err error
329 right, err = strconv.ParseFloat(bv.String(), 64)
330 // Check if float is a special floating value and cast value as string.
331 if math.IsInf(right, 0) || math.IsNaN(right) || err != nil {
332 str := bv.String()
333 rightStr = &str
334 }
335 case reflect.Struct:
336 if hreflect.IsTime(bv.Type()) {
337 right = float64(ns.toTimeUnix(bv))
338 }
339 case reflect.Bool:
340 right = 0
341 if bv.Bool() {
342 right = 1
343 }
344 }
345
346 if leftStr != nil && rightStr != nil {
347 return ns.compareTwoStrings(collator, *leftStr, *rightStr)
348 }
349
350 return left, right
351 }
352
353 func (ns *Namespace) compareTwoStrings(collator *langs.Collator, a, b string) (float64, float64) {
354 if ns.caseInsensitive || collator != nil {
355 var c int
356 if collator != nil {
357 c = collator.CompareStrings(a, b)
358 } else {
359 c = compare.Strings(a, b)
360 }
361 return toLeftRight(c)
362 }
363 return toLeftRight(strings.Compare(a, b))
364 }
365
366 func (ns *Namespace) toTimeUnix(v reflect.Value) int64 {
367 t, ok := hreflect.AsTime(v, ns.loc)
368 if !ok {
369 panic("coding error: argument must be time.Time type reflect Value")
370 }
371 return t.Unix()
372 }