Debian Codegraph @

util/sprig/numeric.go

raw
1 package sprig
2
3 import (
4 "fmt"
5 "math"
6 "math/rand"
7 "reflect"
8 "strconv"
9 "strings"
10 )
11
12 // toFloat64 converts a value to a 64-bit float.
13 // It handles various input types:
14 // - string: parsed as a float, returns 0 if parsing fails
15 // - integer types: converted to float64
16 // - unsigned integer types: converted to float64
17 // - float types: returned as is
18 // - bool: true becomes 1.0, false becomes 0.0
19 // - other types: returns 0.0
20 //
21 // Parameters:
22 // - v: The value to convert to float64
23 //
24 // Returns:
25 // - float64: The converted value
26 func toFloat64(v any) float64 {
27 if str, ok := v.(string); ok {
28 iv, err := strconv.ParseFloat(str, 64)
29 if err != nil {
30 return 0
31 }
32 return iv
33 }
34
35 val := reflect.Indirect(reflect.ValueOf(v))
36 switch val.Kind() {
37 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
38 return float64(val.Int())
39 case reflect.Uint8, reflect.Uint16, reflect.Uint32:
40 return float64(val.Uint())
41 case reflect.Uint, reflect.Uint64:
42 return float64(val.Uint())
43 case reflect.Float32, reflect.Float64:
44 return val.Float()
45 case reflect.Bool:
46 if val.Bool() {
47 return 1
48 }
49 return 0
50 default:
51 return 0
52 }
53 }
54
55 // toInt converts a value to a 32-bit integer.
56 // This is a wrapper around toInt64 that casts the result to int.
57 //
58 // Parameters:
59 // - v: The value to convert to int
60 //
61 // Returns:
62 // - int: The converted value
63 func toInt(v any) int {
64 // It's not optimal. But I don't want duplicate toInt64 code.
65 return int(toInt64(v))
66 }
67
68 // toInt64 converts a value to a 64-bit integer.
69 // It handles various input types:
70 // - string: parsed as an integer, returns 0 if parsing fails
71 // - integer types: converted to int64
72 // - unsigned integer types: converted to int64 (values > MaxInt64 become MaxInt64)
73 // - float types: truncated to int64
74 // - bool: true becomes 1, false becomes 0
75 // - other types: returns 0
76 func toInt64(v any) int64 {
77 if str, ok := v.(string); ok {
78 iv, err := strconv.ParseInt(str, 10, 64)
79 if err != nil {
80 return 0
81 }
82 return iv
83 }
84 val := reflect.Indirect(reflect.ValueOf(v))
85 switch val.Kind() {
86 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
87 return val.Int()
88 case reflect.Uint8, reflect.Uint16, reflect.Uint32:
89 return int64(val.Uint())
90 case reflect.Uint, reflect.Uint64:
91 tv := val.Uint()
92 if tv <= math.MaxInt64 {
93 return int64(tv)
94 }
95 // TODO: What is the sensible thing to do here?
96 return math.MaxInt64
97 case reflect.Float32, reflect.Float64:
98 return int64(val.Float())
99 case reflect.Bool:
100 if val.Bool() {
101 return 1
102 }
103 return 0
104 default:
105 return 0
106 }
107 }
108
109 // add1 increments a value by 1.
110 // The input is first converted to int64 using toInt64.
111 //
112 // Parameters:
113 // - i: The value to increment
114 //
115 // Returns:
116 // - int64: The incremented value
117 func add1(i any) int64 {
118 return toInt64(i) + 1
119 }
120
121 // add sums all the provided values.
122 // All inputs are converted to int64 using toInt64 before addition.
123 //
124 // Parameters:
125 // - i: A variadic list of values to sum
126 //
127 // Returns:
128 // - int64: The sum of all values
129 func add(i ...any) int64 {
130 var a int64
131 for _, b := range i {
132 a += toInt64(b)
133 }
134 return a
135 }
136
137 // sub subtracts the second value from the first.
138 // Both inputs are converted to int64 using toInt64 before subtraction.
139 //
140 // Parameters:
141 // - a: The value to subtract from
142 // - b: The value to subtract
143 //
144 // Returns:
145 // - int64: The result of a - b
146 func sub(a, b any) int64 {
147 return toInt64(a) - toInt64(b)
148 }
149
150 // div divides the first value by the second.
151 // Both inputs are converted to int64 using toInt64 before division.
152 // Note: This performs integer division, so the result is truncated.
153 //
154 // Parameters:
155 // - a: The dividend
156 // - b: The divisor
157 //
158 // Returns:
159 // - int64: The result of a / b
160 //
161 // Panics:
162 // - If b evaluates to 0 (division by zero)
163 func div(a, b any) int64 {
164 return toInt64(a) / toInt64(b)
165 }
166
167 // mod returns the remainder of dividing the first value by the second.
168 // Both inputs are converted to int64 using toInt64 before the modulo operation.
169 //
170 // Parameters:
171 // - a: The dividend
172 // - b: The divisor
173 //
174 // Returns:
175 // - int64: The remainder of a / b
176 //
177 // Panics:
178 // - If b evaluates to 0 (modulo by zero)
179 func mod(a, b any) int64 {
180 return toInt64(a) % toInt64(b)
181 }
182
183 // mul multiplies all the provided values.
184 // All inputs are converted to int64 using toInt64 before multiplication.
185 //
186 // Parameters:
187 // - a: The first value to multiply
188 // - v: Additional values to multiply with a
189 //
190 // Returns:
191 // - int64: The product of all values
192 func mul(a any, v ...any) int64 {
193 val := toInt64(a)
194 for _, b := range v {
195 val = val * toInt64(b)
196 }
197 return val
198 }
199
200 // randInt generates a random integer between min (inclusive) and max (exclusive).
201 //
202 // Parameters:
203 // - min: The lower bound (inclusive)
204 // - max: The upper bound (exclusive)
205 //
206 // Returns:
207 // - int: A random integer in the range [min, max)
208 //
209 // Panics:
210 // - If max <= min (via rand.Intn)
211 func randInt(min, max int) int {
212 return rand.Intn(max-min) + min
213 }
214
215 // maxAsInt64 returns the maximum value from a list of values as an int64.
216 // All inputs are converted to int64 using toInt64 before comparison.
217 //
218 // Parameters:
219 // - a: The first value to compare
220 // - i: Additional values to compare
221 //
222 // Returns:
223 // - int64: The maximum value from all inputs
224 func maxAsInt64(a any, i ...any) int64 {
225 aa := toInt64(a)
226 for _, b := range i {
227 bb := toInt64(b)
228 if bb > aa {
229 aa = bb
230 }
231 }
232 return aa
233 }
234
235 // maxAsFloat64 returns the maximum value from a list of values as a float64.
236 // All inputs are converted to float64 using toFloat64 before comparison.
237 //
238 // Parameters:
239 // - a: The first value to compare
240 // - i: Additional values to compare
241 //
242 // Returns:
243 // - float64: The maximum value from all inputs
244 func maxAsFloat64(a any, i ...any) float64 {
245 m := toFloat64(a)
246 for _, b := range i {
247 m = math.Max(m, toFloat64(b))
248 }
249 return m
250 }
251
252 // minAsInt64 returns the minimum value from a list of values as an int64.
253 // All inputs are converted to int64 using toInt64 before comparison.
254 //
255 // Parameters:
256 // - a: The first value to compare
257 // - i: Additional values to compare
258 //
259 // Returns:
260 // - int64: The minimum value from all inputs
261 func minAsInt64(a any, i ...any) int64 {
262 aa := toInt64(a)
263 for _, b := range i {
264 bb := toInt64(b)
265 if bb < aa {
266 aa = bb
267 }
268 }
269 return aa
270 }
271
272 // minAsFloat64 returns the minimum value from a list of values as a float64.
273 // All inputs are converted to float64 using toFloat64 before comparison.
274 //
275 // Parameters:
276 // - a: The first value to compare
277 // - i: Additional values to compare
278 //
279 // Returns:
280 // - float64: The minimum value from all inputs
281 func minAsFloat64(a any, i ...any) float64 {
282 m := toFloat64(a)
283 for _, b := range i {
284 m = math.Min(m, toFloat64(b))
285 }
286 return m
287 }
288
289 // until generates a sequence of integers from 0 to count (exclusive).
290 // If count is negative, it generates a sequence from 0 to count (inclusive) with step -1.
291 //
292 // Parameters:
293 // - count: The end value (exclusive if positive, inclusive if negative)
294 //
295 // Returns:
296 // - []int: A slice containing the generated sequence
297 func until(count int) []int {
298 step := 1
299 if count < 0 {
300 step = -1
301 }
302 return untilStep(0, count, step)
303 }
304
305 // untilStep generates a sequence of integers from start to stop with the specified step.
306 // The sequence is generated as follows:
307 // - If step is 0, returns an empty slice
308 // - If stop < start and step < 0, generates a decreasing sequence from start to stop (exclusive)
309 // - If stop > start and step > 0, generates an increasing sequence from start to stop (exclusive)
310 // - Otherwise, returns an empty slice
311 //
312 // Parameters:
313 // - start: The starting value (inclusive)
314 // - stop: The ending value (exclusive)
315 // - step: The increment between values
316 //
317 // Returns:
318 // - []int: A slice containing the generated sequence
319 //
320 // Panics:
321 // - If the number of iterations would exceed loopExecutionLimit
322 func untilStep(start, stop, step int) []int {
323 var v []int
324 if step == 0 {
325 return v
326 }
327 iterations := math.Abs(float64(stop)-float64(start)) / float64(step)
328 if iterations > loopExecutionLimit {
329 panic(fmt.Sprintf("too many iterations in untilStep; max allowed is %d, got %f", loopExecutionLimit, iterations))
330 }
331 if stop < start {
332 if step >= 0 {
333 return v
334 }
335 for i := start; i > stop; i += step {
336 v = append(v, i)
337 }
338 return v
339 }
340 if step <= 0 {
341 return v
342 }
343 for i := start; i < stop; i += step {
344 v = append(v, i)
345 }
346 return v
347 }
348
349 // floor returns the greatest integer value less than or equal to the input.
350 // The input is first converted to float64 using toFloat64.
351 //
352 // Parameters:
353 // - a: The value to floor
354 //
355 // Returns:
356 // - float64: The greatest integer value less than or equal to a
357 func floor(a any) float64 {
358 return math.Floor(toFloat64(a))
359 }
360
361 // ceil returns the least integer value greater than or equal to the input.
362 // The input is first converted to float64 using toFloat64.
363 //
364 // Parameters:
365 // - a: The value to ceil
366 //
367 // Returns:
368 // - float64: The least integer value greater than or equal to a
369 func ceil(a any) float64 {
370 return math.Ceil(toFloat64(a))
371 }
372
373 // round rounds a number to a specified number of decimal places.
374 // The input is first converted to float64 using toFloat64.
375 //
376 // Parameters:
377 // - a: The value to round
378 // - p: The number of decimal places to round to
379 // - rOpt: Optional rounding threshold (default is 0.5)
380 //
381 // Returns:
382 // - float64: The rounded value
383 //
384 // Examples:
385 // - round(3.14159, 2) returns 3.14
386 // - round(3.14159, 2, 0.6) returns 3.14 (only rounds up if fraction ≥ 0.6)
387 func round(a any, p int, rOpt ...float64) float64 {
388 roundOn := .5
389 if len(rOpt) > 0 {
390 roundOn = rOpt[0]
391 }
392 val := toFloat64(a)
393 places := toFloat64(p)
394 var round float64
395 pow := math.Pow(10, places)
396 digit := pow * val
397 _, div := math.Modf(digit)
398 if div >= roundOn {
399 round = math.Ceil(digit)
400 } else {
401 round = math.Floor(digit)
402 }
403 return round / pow
404 }
405
406 // toDecimal converts a value from octal to decimal.
407 // The input is first converted to a string using fmt.Sprint, then parsed as an octal number.
408 // If the parsing fails, it returns 0.
409 //
410 // Parameters:
411 // - v: The octal value to convert
412 //
413 // Returns:
414 // - int64: The decimal representation of the octal value
415 func toDecimal(v any) int64 {
416 result, err := strconv.ParseInt(fmt.Sprint(v), 8, 64)
417 if err != nil {
418 return 0
419 }
420 return result
421 }
422
423 // atoi converts a string to an integer.
424 // If the conversion fails, it returns 0.
425 //
426 // Parameters:
427 // - a: The string to convert
428 //
429 // Returns:
430 // - int: The integer value of the string
431 func atoi(a string) int {
432 i, _ := strconv.Atoi(a)
433 return i
434 }
435
436 // seq generates a sequence of integers and returns them as a space-delimited string.
437 // The behavior depends on the number of parameters:
438 // - 0 params: Returns an empty string
439 // - 1 param: Generates sequence from 1 to param[0]
440 // - 2 params: Generates sequence from param[0] to param[1]
441 // - 3 params: Generates sequence from param[0] to param[2] with step param[1]
442 //
443 // If the end is less than the start, the sequence will be decreasing unless
444 // a positive step is explicitly provided (which would result in an empty string).
445 //
446 // Parameters:
447 // - params: Variable number of integers defining the sequence
448 //
449 // Returns:
450 // - string: A space-delimited string of the generated sequence
451 func seq(params ...int) string {
452 increment := 1
453 switch len(params) {
454 case 0:
455 return ""
456 case 1:
457 start := 1
458 end := params[0]
459 if end < start {
460 increment = -1
461 }
462 return intArrayToString(untilStep(start, end+increment, increment), " ")
463 case 3:
464 start := params[0]
465 end := params[2]
466 step := params[1]
467 if end < start {
468 increment = -1
469 if step > 0 {
470 return ""
471 }
472 }
473 return intArrayToString(untilStep(start, end+increment, step), " ")
474 case 2:
475 start := params[0]
476 end := params[1]
477 step := 1
478 if end < start {
479 step = -1
480 }
481 return intArrayToString(untilStep(start, end+step, step), " ")
482 default:
483 return ""
484 }
485 }
486
487 // intArrayToString converts a slice of integers to a space-delimited string.
488 // The function removes the square brackets that would normally appear when
489 // converting a slice to a string.
490 //
491 // Parameters:
492 // - slice: The slice of integers to convert
493 // - delimiter: The delimiter to use between elements
494 //
495 // Returns:
496 // - string: A delimited string representation of the integer slice
497 func intArrayToString(slice []int, delimiter string) string {
498 return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(slice)), delimiter), "[]")
499 }