-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathnative_numeric.go
More file actions
660 lines (595 loc) · 19.9 KB
/
Copy pathnative_numeric.go
File metadata and controls
660 lines (595 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright 2023-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package protovalidate
import (
"fmt"
"math"
"slices"
"strconv"
"strings"
"buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// numericValue is the set of Go types that back protobuf numeric field kinds.
type numericValue interface {
~int32 | ~int64 | ~uint32 | ~uint64 | ~float32 | ~float64
}
// Per-kind builder wrappers. Each handles nil check and type-specific
// concerns before delegating to the generic builder.
func tryBuildNativeInt32Rules(base base, rules *validate.Int32Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &int32Config)
}
func tryBuildNativeSint32Rules(base base, rules *validate.SInt32Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &sint32Config)
}
func tryBuildNativeSfixed32Rules(base base, rules *validate.SFixed32Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &sfixed32Config)
}
func tryBuildNativeInt64Rules(base base, rules *validate.Int64Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &int64Config)
}
func tryBuildNativeSint64Rules(base base, rules *validate.SInt64Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &sint64Config)
}
func tryBuildNativeSfixed64Rules(base base, rules *validate.SFixed64Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &sfixed64Config)
}
func tryBuildNativeUint32Rules(base base, rules *validate.UInt32Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &uint32Config)
}
func tryBuildNativeFixed32Rules(base base, rules *validate.Fixed32Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &fixed32Config)
}
func tryBuildNativeUint64Rules(base base, rules *validate.UInt64Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &uint64Config)
}
func tryBuildNativeFixed64Rules(base base, rules *validate.Fixed64Rules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &fixed64Config)
}
func tryBuildNativeFloatRules(base base, rules *validate.FloatRules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &floatConfig)
}
func tryBuildNativeDoubleRules(base base, rules *validate.DoubleRules) evaluator {
if rules == nil {
return nil
}
return tryBuildNativeNumericRules(base, rules, &doubleConfig)
}
// tryBuildNativeNumericRules attempts to build a native Go evaluator for
// numeric rules. Returns nil if the rules can't be handled natively,
// including cases with unknown fields (custom predefined extensions).
func tryBuildNativeNumericRules[T numericValue, R numericRules[T]](
base base,
rules R,
config *numericTypeConfig[T],
) evaluator {
// Bail out if the rules message has unknown fields, which indicate
// custom predefined extensions that we can't handle natively.
if len(rules.ProtoReflect().GetUnknown()) > 0 {
return nil
}
hasRule := false
// bail out if there's a gt/lt and the value is NaN
// (it's an invalid protovalidate rule; let CEL return the error)
var lowerValue T
lower := lowerBoundNone
switch {
case rules.HasGt():
lower = lowerBoundGt
lowerValue = rules.GetGt()
if math.IsNaN(float64(lowerValue)) {
return nil
}
rules.ProtoReflect().Clear(config.descs.gtSite.desc)
hasRule = true
case rules.HasGte():
lower = lowerBoundGte
lowerValue = rules.GetGte()
if math.IsNaN(float64(lowerValue)) {
return nil
}
rules.ProtoReflect().Clear(config.descs.gteSite.desc)
hasRule = true
}
var upperValue T
upper := upperBoundNone
switch {
case rules.HasLt():
upper = upperBoundLt
upperValue = rules.GetLt()
if math.IsNaN(float64(upperValue)) {
return nil
}
rules.ProtoReflect().Clear(config.descs.ltSite.desc)
hasRule = true
case rules.HasLte():
upper = upperBoundLte
upperValue = rules.GetLte()
if math.IsNaN(float64(upperValue)) {
return nil
}
rules.ProtoReflect().Clear(config.descs.lteSite.desc)
hasRule = true
}
var constVal *T
if rules.HasConst() {
constVal = ptr(rules.GetConst())
rules.ProtoReflect().Clear(config.descs.constSite.desc)
hasRule = true
}
var inVals []T
if inVals = rules.GetIn(); len(inVals) > 0 {
rules.ProtoReflect().Clear(config.descs.inSite.desc)
hasRule = true
}
var notInVals []T
if notInVals = rules.GetNotIn(); len(notInVals) > 0 {
rules.ProtoReflect().Clear(config.descs.notInSite.desc)
hasRule = true
}
type finiteInterface interface {
HasFinite() bool
GetFinite() bool
}
finite := false
if fi, ok := (any)(rules).(finiteInterface); ok && fi.HasFinite() {
finite = fi.GetFinite()
rules.ProtoReflect().Clear(config.descs.finiteSite.desc)
hasRule = true
}
if !hasRule {
return nil
}
return nativeNumericCompare[T]{
base: base,
config: config,
lo: lowerValue,
lower: lower,
hi: upperValue,
upper: upper,
constVal: constVal,
inVals: inVals,
notInVals: notInVals,
finite: finite,
}
}
// numericRules is satisfied by all generated numeric rules types
// (Int32Rules, Int64Rules, UInt32Rules, etc.).
//
//nolint:interfacebloat
type numericRules[T numericValue] interface {
HasGt() bool
GetGt() T
HasGte() bool
GetGte() T
HasLt() bool
GetLt() T
HasLte() bool
GetLte() T
HasConst() bool
GetConst() T
GetIn() []T
GetNotIn() []T
ProtoReflect() protoreflect.Message
}
// numericDescriptors bundles the pre-built rule sites for a single numeric
// rules type (e.g., Int32Rules). A ruleSite carries both the rule-path
// FieldPathElements and the leaf descriptor, so the individual per-rule
// descriptor fields are not needed.
type numericDescriptors struct {
gtSite ruleSite
gteSite ruleSite
ltSite ruleSite
lteSite ruleSite
constSite ruleSite
inSite ruleSite
notInSite ruleSite
finiteSite ruleSite // zero-valued for non-float kinds
}
func makeNumericDescriptors(
fieldName string,
rulesMsg protoreflect.ProtoMessage,
typeName string,
) numericDescriptors {
rulesDesc := rulesMsg.ProtoReflect().Descriptor()
ruleDesc := fieldRulesDesc.Fields().ByName(protoreflect.Name(fieldName))
var finiteDesc protoreflect.FieldDescriptor
if rulesDesc.Name() == "FloatRules" || rulesDesc.Name() == "DoubleRules" {
finiteDesc = rulesDesc.Fields().ByName("finite")
}
descriptors := numericDescriptors{
gtSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("gt"), "", ""),
gteSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("gte"), "", ""),
ltSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("lt"), "", ""),
lteSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("lte"), "", ""),
constSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("const"), typeName+".const", ""),
inSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("in"), typeName+".in", ""),
notInSite: makeRuleSite(ruleDesc, rulesDesc.Fields().ByName("not_in"), typeName+".not_in", ""),
}
if finiteDesc != nil {
descriptors.finiteSite = makeRuleSite(ruleDesc, finiteDesc, typeName+".finite", "must be finite")
}
return descriptors
}
// numericTypeConfig holds all type-specific operations and metadata
// for a single proto numeric kind.
type numericTypeConfig[T numericValue] struct {
typeName string // proto rule prefix: "int32", "sint32", "float", etc.
descs numericDescriptors // descriptor bundle for rule path construction
extractVal func(protoreflect.Value) T // val.Int/Uint/Float + cast
makeRuleVal func(T) protoreflect.Value // ValueOfInt32, ValueOfFloat32, etc.
newRules func() proto.Message // fresh rules message, used to build in/not_in rule values
nanFailsRange bool // true only for float32, float64
}
//nolint:gochecknoglobals
var (
int32Config = numericTypeConfig[int32]{
typeName: "int32",
descs: makeNumericDescriptors("int32", (*validate.Int32Rules)(nil), "int32"),
extractVal: func(v protoreflect.Value) int32 { return int32(v.Int()) },
makeRuleVal: protoreflect.ValueOfInt32,
newRules: func() proto.Message { return &validate.Int32Rules{} },
}
sint32Config = numericTypeConfig[int32]{
typeName: "sint32",
descs: makeNumericDescriptors("sint32", (*validate.SInt32Rules)(nil), "sint32"),
extractVal: func(v protoreflect.Value) int32 { return int32(v.Int()) },
makeRuleVal: protoreflect.ValueOfInt32,
newRules: func() proto.Message { return &validate.SInt32Rules{} },
}
sfixed32Config = numericTypeConfig[int32]{
typeName: "sfixed32",
descs: makeNumericDescriptors("sfixed32", (*validate.SFixed32Rules)(nil), "sfixed32"),
extractVal: func(v protoreflect.Value) int32 { return int32(v.Int()) },
makeRuleVal: protoreflect.ValueOfInt32,
newRules: func() proto.Message { return &validate.SFixed32Rules{} },
}
int64Config = numericTypeConfig[int64]{
typeName: "int64",
descs: makeNumericDescriptors("int64", (*validate.Int64Rules)(nil), "int64"),
extractVal: func(v protoreflect.Value) int64 { return v.Int() },
makeRuleVal: protoreflect.ValueOfInt64,
newRules: func() proto.Message { return &validate.Int64Rules{} },
}
sint64Config = numericTypeConfig[int64]{
typeName: "sint64",
descs: makeNumericDescriptors("sint64", (*validate.SInt64Rules)(nil), "sint64"),
extractVal: func(v protoreflect.Value) int64 { return v.Int() },
makeRuleVal: protoreflect.ValueOfInt64,
newRules: func() proto.Message { return &validate.SInt64Rules{} },
}
sfixed64Config = numericTypeConfig[int64]{
typeName: "sfixed64",
descs: makeNumericDescriptors("sfixed64", (*validate.SFixed64Rules)(nil), "sfixed64"),
extractVal: func(v protoreflect.Value) int64 { return v.Int() },
makeRuleVal: protoreflect.ValueOfInt64,
newRules: func() proto.Message { return &validate.SFixed64Rules{} },
}
uint32Config = numericTypeConfig[uint32]{
typeName: "uint32",
descs: makeNumericDescriptors("uint32", (*validate.UInt32Rules)(nil), "uint32"),
extractVal: func(v protoreflect.Value) uint32 { return uint32(v.Uint()) },
makeRuleVal: protoreflect.ValueOfUint32,
newRules: func() proto.Message { return &validate.UInt32Rules{} },
}
fixed32Config = numericTypeConfig[uint32]{
typeName: "fixed32",
descs: makeNumericDescriptors("fixed32", (*validate.Fixed32Rules)(nil), "fixed32"),
extractVal: func(v protoreflect.Value) uint32 { return uint32(v.Uint()) },
makeRuleVal: protoreflect.ValueOfUint32,
newRules: func() proto.Message { return &validate.Fixed32Rules{} },
}
uint64Config = numericTypeConfig[uint64]{
typeName: "uint64",
descs: makeNumericDescriptors("uint64", (*validate.UInt64Rules)(nil), "uint64"),
extractVal: func(v protoreflect.Value) uint64 { return v.Uint() },
makeRuleVal: protoreflect.ValueOfUint64,
newRules: func() proto.Message { return &validate.UInt64Rules{} },
}
fixed64Config = numericTypeConfig[uint64]{
typeName: "fixed64",
descs: makeNumericDescriptors("fixed64", (*validate.Fixed64Rules)(nil), "fixed64"),
extractVal: func(v protoreflect.Value) uint64 { return v.Uint() },
makeRuleVal: protoreflect.ValueOfUint64,
newRules: func() proto.Message { return &validate.Fixed64Rules{} },
}
floatConfig = numericTypeConfig[float32]{
typeName: "float",
descs: makeNumericDescriptors("float", (*validate.FloatRules)(nil), "float"),
extractVal: func(v protoreflect.Value) float32 { return float32(v.Float()) },
makeRuleVal: protoreflect.ValueOfFloat32,
newRules: func() proto.Message { return &validate.FloatRules{} },
nanFailsRange: true,
}
doubleConfig = numericTypeConfig[float64]{
typeName: "double",
descs: makeNumericDescriptors("double", (*validate.DoubleRules)(nil), "double"),
extractVal: func(v protoreflect.Value) float64 { return v.Float() },
makeRuleVal: protoreflect.ValueOfFloat64,
newRules: func() proto.Message { return &validate.DoubleRules{} },
nanFailsRange: true,
}
)
// lowerBound describes which lower bound constraint is active.
type lowerBound int
const (
lowerBoundNone lowerBound = iota
// lowerBoundGte is an inclusive lower bound (>=).
lowerBoundGte
// lowerBoundGt is an exclusive lower bound (>).
lowerBoundGt
)
// upperBound describes which upper bound constraint is active.
type upperBound int
const (
upperBoundNone upperBound = iota
upperBoundLt
upperBoundLte
)
// nativeNumericCompare is a native Go evaluator for numeric gt/gte/lt/lte/
// const/in/not_in rules. It replaces CEL evaluation with direct Go comparisons.
//
// config is stored as a pointer so the (globally shared, read-only) config
// struct is not copied into every evaluator (and then again onto the stack
// via the value receiver on Evaluate).
type nativeNumericCompare[T numericValue] struct {
base
config *numericTypeConfig[T]
lo T // lower bound value (gt or gte threshold)
lower lowerBound // gt (exclusive) or gte (inclusive)
hi T // upper bound value (lt or lte threshold)
upper upperBound // none, lt, or lte
constVal *T // constant value for comparison
inVals []T // slice of values for IN comparison
notInVals []T // slice of values for NOT_IN comparison
finite bool // true if the value is finite (not NaN or Infinity)
}
// belowLo reports whether v violates the lower bound.
func (n nativeNumericCompare[T]) belowLo(v T) bool {
if n.lower == lowerBoundGt {
return v <= n.lo
}
return v < n.lo
}
// aboveHi reports whether v violates the upper bound.
func (n nativeNumericCompare[T]) aboveHi(v T) bool {
if n.upper == upperBoundLt {
return v >= n.hi
}
return v > n.hi
}
// isNormalRange reports whether lo and hi form a normal (non-exclusive) range.
func (n nativeNumericCompare[T]) isNormalRange() bool {
return n.hi >= n.lo
}
func (n nativeNumericCompare[T]) loSite() ruleSite {
if n.lower == lowerBoundGt {
return n.config.descs.gtSite
}
return n.config.descs.gteSite
}
func (n nativeNumericCompare[T]) hiSite() ruleSite {
if n.upper == upperBoundLt {
return n.config.descs.ltSite
}
return n.config.descs.lteSite
}
func (n nativeNumericCompare[T]) gtRulePrefix() string {
if n.lower == lowerBoundGt {
return n.config.typeName + ".gt"
}
return n.config.typeName + ".gte"
}
func (n nativeNumericCompare[T]) ltRulePrefix() string {
if n.upper == upperBoundLt {
return n.config.typeName + ".lt"
}
return n.config.typeName + ".lte"
}
func (n nativeNumericCompare[T]) gtltRule() string {
if n.lower != lowerBoundNone {
prefix := n.gtRulePrefix()
switch n.upper {
case upperBoundLt:
prefix += "_lt"
if !n.isNormalRange() {
prefix += "_exclusive"
}
case upperBoundLte:
prefix += "_lte"
if !n.isNormalRange() {
prefix += "_exclusive"
}
}
return prefix
}
return n.ltRulePrefix()
}
func (n nativeNumericCompare[T]) loMessage() string {
if n.lower == lowerBoundGt {
return "greater than " + format(n.lo)
}
return "greater than or equal to " + format(n.lo)
}
func (n nativeNumericCompare[T]) hiMessage() string {
if n.upper == upperBoundLt {
return "less than " + format(n.hi)
}
return "less than or equal to " + format(n.hi)
}
func (n nativeNumericCompare[T]) conjunction() string {
if n.isNormalRange() {
return "and"
}
return "or"
}
func (n nativeNumericCompare[T]) Evaluate(_ protoreflect.Message, val protoreflect.Value, cfg *validationConfig) error {
valT := n.config.extractVal(val)
var violations []*Violation
if n.constVal != nil && valT != *n.constVal {
violations = append(violations, n.newViolation(n.config.descs.constSite,
n.config.typeName+".const",
"must equal "+format(*n.constVal),
val, n.config.makeRuleVal(*n.constVal)))
if cfg.failFast {
return &ValidationError{Violations: violations}
}
}
if len(n.inVals) > 0 && !slices.Contains(n.inVals, valT) {
violations = append(violations, n.newViolation(n.config.descs.inSite,
n.config.typeName+".in",
"must be in list "+formatList(n.inVals),
val, sliceToListValue(n.config.newRules(), n.config.descs.inSite.desc, n.inVals, n.config.makeRuleVal)))
if cfg.failFast {
return &ValidationError{Violations: violations}
}
}
if len(n.notInVals) > 0 && slices.Contains(n.notInVals, valT) {
violations = append(violations, n.newViolation(n.config.descs.notInSite,
n.config.typeName+".not_in",
"must not be in list "+formatList(n.notInVals),
val, sliceToListValue(n.config.newRules(), n.config.descs.notInSite.desc, n.notInVals, n.config.makeRuleVal)))
if cfg.failFast {
return &ValidationError{Violations: violations}
}
}
if n.finite && (math.IsNaN(float64(valT)) || math.IsInf(float64(valT), 0)) {
violations = append(violations, n.newViolation(n.config.descs.finiteSite,
n.config.typeName+".finite",
"must be finite",
val, protoreflect.ValueOfBool(true)))
if cfg.failFast {
return &ValidationError{Violations: violations}
}
}
if v := n.evaluateRange(valT, val); v != nil {
violations = append(violations, v)
if cfg.failFast {
return &ValidationError{Violations: violations}
}
}
if len(violations) > 0 {
return &ValidationError{
Violations: violations,
}
}
return nil
}
// evaluateRange returns a violation for lower/upper bound checks, or nil.
// Split out of Evaluate so that the hot path (no range rules) stays small
// enough to inline.
func (n nativeNumericCompare[T]) evaluateRange(valT T, val protoreflect.Value) *Violation {
if n.lower == lowerBoundNone && n.upper == upperBoundNone {
return nil
}
// For float/double, NaN fails all range checks (matches CEL behavior).
isNaN := n.config.nanFailsRange && math.IsNaN(float64(valT))
switch {
case n.lower == lowerBoundNone:
if isNaN || n.aboveHi(valT) {
return n.newViolation(n.hiSite(),
n.gtltRule(), "must be "+n.hiMessage(),
val, n.config.makeRuleVal(n.hi))
}
case n.upper == upperBoundNone:
if isNaN || n.belowLo(valT) {
return n.newViolation(n.loSite(),
n.gtltRule(), "must be "+n.loMessage(),
val, n.config.makeRuleVal(n.lo))
}
default:
var failure bool
if n.isNormalRange() {
failure = isNaN || n.aboveHi(valT) || n.belowLo(valT)
} else {
failure = isNaN || (n.aboveHi(valT) && n.belowLo(valT))
}
if failure {
return n.newViolation(n.loSite(),
n.gtltRule(),
fmt.Sprintf("must be %s %s %s", n.loMessage(), n.conjunction(), n.hiMessage()),
val, n.config.makeRuleVal(n.lo))
}
}
return nil
}
func (n nativeNumericCompare[T]) Tautology() bool {
return false
}
var _ evaluator = nativeNumericCompare[int32]{}
func ptr[T any](v T) *T { return &v }
// formatList formats a slice as "list [val1, val2]" to match CEL message format.
func formatList[T any](vals []T) string {
parts := make([]string, len(vals))
for i, v := range vals {
parts[i] = format(v)
}
return "[" + strings.Join(parts, ", ") + "]"
}
func format(v any) string {
switch val := v.(type) {
case float32:
return printFloat(float64(val))
case float64:
return printFloat(val)
default:
return fmt.Sprintf("%v", val)
}
}
func printFloat(argDbl float64) string {
if math.IsNaN(argDbl) {
return "NaN"
}
if math.IsInf(argDbl, -1) {
return "-Infinity"
}
if math.IsInf(argDbl, 1) {
return "Infinity"
}
return strconv.FormatFloat(argDbl, 'f', -1, 64)
}