-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfloat_validator.go
454 lines (378 loc) · 10.8 KB
/
float_validator.go
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
package validator
import (
"bytes"
"context"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"github.com/go-courier/ptr"
"github.com/go-courier/validator/errors"
"github.com/go-courier/validator/rules"
)
var (
TargetFloatValue = "float value"
TargetDecimalDigitsOfFloatValue = "decimal digits of float value"
TargetTotalDigitsOfFloatValue = "total digits of float value"
)
/*
Validator for float32 and float64
Rules:
ranges
@float[min,max]
@float[1,10] // value should large or equal than 1 and less or equal than 10
@float(1,10] // value should large than 1 and less or equal than 10
@float[1,10) // value should large or equal than 1
@float[1,) // value should large or equal than 1
@float[,1) // value should less than 1
enumeration
@float{1.1,1.2,1.3} // value should be one of these
multiple of some float value
@float{%multipleOf}
@float{%2.2} // value should be multiple of 2.2
max digits and decimal digits.
when defined, all values in rule should be under range of them.
@float<MAX_DIGITS,DECIMAL_DIGITS>
@float<5,2> // will checkout these values invalid: 1.111 (decimal digits too many), 12345.6 (digits too many)
composes
@float<MAX_DIGITS,DECIMAL_DIGITS>[min,max]
aliases:
@float32 = @float<7>
@float64 = @float<15>
*/
type FloatValidator struct {
MaxDigits uint
DecimalDigits *uint
Minimum *float64
Maximum *float64
ExclusiveMaximum bool
ExclusiveMinimum bool
MultipleOf float64
Enums map[float64]string
}
func init() {
ValidatorMgrDefault.Register(&FloatValidator{})
}
func (validator *FloatValidator) SetDefaults() {
if validator != nil {
if validator.MaxDigits == 0 {
validator.MaxDigits = 7
}
if validator.DecimalDigits == nil {
validator.DecimalDigits = ptr.Uint(2)
}
}
}
func (FloatValidator) Names() []string {
return []string{"float", "double", "float32", "float64"}
}
func isFloatType(typ reflect.Type) bool {
switch typ.Kind() {
case reflect.Float32, reflect.Float64:
return true
}
return false
}
func (validator *FloatValidator) Validate(v interface{}) error {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
if !isFloatType(rv.Type()) {
return errors.NewUnsupportedTypeError(rv.Type().String(), validator.String())
}
val := rv.Float()
decimalDigits := *validator.DecimalDigits
m, d := lengthOfDigits(val)
if m > validator.MaxDigits {
return &errors.OutOfRangeError{
Target: TargetTotalDigitsOfFloatValue,
Current: m,
Maximum: validator.MaxDigits,
}
}
if d > decimalDigits {
return &errors.OutOfRangeError{
Target: TargetDecimalDigitsOfFloatValue,
Current: d,
Maximum: decimalDigits,
}
}
if validator.Enums != nil {
if _, ok := validator.Enums[val]; !ok {
values := make([]interface{}, 0)
for _, v := range validator.Enums {
values = append(values, v)
}
return &errors.NotInEnumError{
Target: TargetFloatValue,
Current: v,
Enums: values,
}
}
return nil
}
if validator.Minimum != nil {
mininum := *validator.Minimum
if (validator.ExclusiveMinimum && val == mininum) || val < mininum {
return &errors.OutOfRangeError{
Target: TargetFloatValue,
Current: val,
Minimum: mininum,
ExclusiveMinimum: validator.ExclusiveMinimum,
}
}
}
if validator.Maximum != nil {
maxinum := *validator.Maximum
if (validator.ExclusiveMaximum && val == maxinum) || val > maxinum {
return &errors.OutOfRangeError{
Target: TargetFloatValue,
Current: val,
Maximum: maxinum,
ExclusiveMaximum: validator.ExclusiveMaximum,
}
}
}
if validator.MultipleOf != 0 {
if !multipleOf(val, validator.MultipleOf, decimalDigits) {
return &errors.MultipleOfError{
Target: TargetFloatValue,
Current: val,
MultipleOf: validator.MultipleOf,
}
}
}
return nil
}
func lengthOfDigits(f float64) (uint, uint) {
s := strconv.FormatFloat(f, 'e', -1, 64)
var n, d int
parts := strings.Split(s, "e")
nd := strings.Split(parts[0], ".")
i := nd[0]
n = len(i)
if len(nd) == 2 {
d = len(nd[1])
}
if len(parts) == 2 {
switch parts[1][0] {
case '+':
v, _ := strconv.ParseUint(parts[1][1:], 10, 64)
n = n + int(v)
d = d - int(v)
if d < 0 {
d = 0
}
case '-':
v, _ := strconv.ParseUint(parts[1][1:], 10, 64)
n = n - int(v)
if n <= 0 {
n = 1
}
d = d + int(v)
}
}
if math.Abs(f) < 1.0 {
n = 0
}
return uint(n + d), uint(d)
}
func multipleOf(v float64, div float64, decimalDigits uint) bool {
val := round(v/div, int(decimalDigits))
return val == math.Trunc(val)
}
func round(f float64, n int) float64 {
res, _ := strconv.ParseFloat(strconv.FormatFloat(f, 'f', n, 64), 64)
return res
}
func (FloatValidator) New(ctx context.Context, rule *Rule) (Validator, error) {
validator := &FloatValidator{}
switch rule.Name {
case "float", "float32":
validator.MaxDigits = 7
case "double", "float64":
validator.MaxDigits = 15
}
if rule.Params != nil {
if len(rule.Params) > 2 {
return nil, fmt.Errorf("float should only 1 or 2 parameter, but got %d", len(rule.Params))
}
maxDigitsBytes := rule.Params[0].Bytes()
if len(maxDigitsBytes) > 0 {
maxDigits, err := strconv.ParseUint(string(maxDigitsBytes), 10, 4)
if err != nil {
return nil, errors.NewSyntaxError("decimal digits should be a uint value which less than 16, but got `%s`", maxDigitsBytes)
}
validator.MaxDigits = uint(maxDigits)
}
if len(rule.Params) > 1 {
decimalDigitsBytes := rule.Params[1].Bytes()
if len(decimalDigitsBytes) > 0 {
decimalDigits, err := strconv.ParseUint(string(decimalDigitsBytes), 10, 4)
if err != nil || uint(decimalDigits) >= validator.MaxDigits {
return nil, errors.NewSyntaxError("decimal digits should be a uint value which less than %d, but got `%s`", validator.MaxDigits, decimalDigitsBytes)
}
validator.DecimalDigits = ptr.Uint(uint(decimalDigits))
}
}
}
validator.SetDefaults()
validator.ExclusiveMinimum = rule.ExclusiveLeft
validator.ExclusiveMaximum = rule.ExclusiveRight
if rule.Range != nil {
min, max, err := floatRange(
"float",
validator.MaxDigits, validator.DecimalDigits,
rule.Range...,
)
if err != nil {
return nil, err
}
validator.Minimum = min
validator.Maximum = max
validator.ExclusiveMinimum = rule.ExclusiveLeft
validator.ExclusiveMaximum = rule.ExclusiveRight
}
ruleValues := rule.ComputedValues()
if ruleValues != nil {
if len(ruleValues) == 1 {
mayBeMultipleOf := ruleValues[0].Bytes()
if mayBeMultipleOf[0] == '%' {
v := mayBeMultipleOf[1:]
multipleOf, err := parseFloat(v, validator.MaxDigits, validator.DecimalDigits)
if err != nil {
return nil, errors.NewSyntaxError("multipleOf should be a valid float<%d> value, but got `%s`", validator.MaxDigits, v)
}
validator.MultipleOf = multipleOf
}
}
if validator.MultipleOf == 0 {
validator.Enums = map[float64]string{}
for _, v := range ruleValues {
b := v.Bytes()
enumValue, err := parseFloat(b, validator.MaxDigits, validator.DecimalDigits)
if err != nil {
return nil, errors.NewSyntaxError("enum should be a valid float<%d> value, but got `%s`", validator.MaxDigits, b)
}
validator.Enums[enumValue] = string(b)
}
}
}
return validator, validator.TypeCheck(rule)
}
func (validator *FloatValidator) TypeCheck(rule *Rule) error {
switch rule.Type.Kind() {
case reflect.Float32:
if validator.MaxDigits > 7 {
return fmt.Errorf("max digits too large for type %s", rule)
}
return nil
case reflect.Float64:
return nil
}
return errors.NewUnsupportedTypeError(rule.String(), validator.String())
}
func floatRange(typ string, maxDigits uint, decimalDigits *uint, ranges ...*rules.RuleLit) (*float64, *float64, error) {
fullType := fmt.Sprintf("%s<%d>", typ, maxDigits)
if decimalDigits != nil {
fullType = fmt.Sprintf("%s<%d,%d>", typ, maxDigits, *decimalDigits)
}
parseMaybeFloat := func(b []byte) (*float64, error) {
if len(b) == 0 {
return nil, nil
}
n, err := parseFloat(b, maxDigits, decimalDigits)
if err != nil {
return nil, fmt.Errorf("%s value is not correct: %s", fullType, err)
}
return &n, nil
}
switch len(ranges) {
case 2:
min, err := parseMaybeFloat(ranges[0].Bytes())
if err != nil {
return nil, nil, fmt.Errorf("min %s", err)
}
max, err := parseMaybeFloat(ranges[1].Bytes())
if err != nil {
return nil, nil, fmt.Errorf("max %s", err)
}
if min != nil && max != nil && *max < *min {
return nil, nil, fmt.Errorf("max %s value must be equal or large than min value %v, current %v", fullType, *min, *max)
}
return min, max, nil
case 1:
min, err := parseMaybeFloat(ranges[0].Bytes())
if err != nil {
return nil, nil, fmt.Errorf("min %s", err)
}
return min, min, nil
}
return nil, nil, nil
}
func parseFloat(b []byte, maxDigits uint, maybeDecimalDigits *uint) (float64, error) {
f, err := strconv.ParseFloat(string(b), 64)
if err != nil {
return 0, err
}
if b[0] == '-' {
b = b[1:]
}
if b[0] == '.' {
b = append([]byte("0"), b...)
}
i := bytes.IndexRune(b, '.')
decimalDigits := maxDigits - 1
if maybeDecimalDigits != nil && *maybeDecimalDigits < maxDigits {
decimalDigits = *maybeDecimalDigits
}
m := uint(len(b) - 1)
if uint(len(b)-1) > maxDigits {
return 0, fmt.Errorf("max digits should be less than %d, but got %d", decimalDigits, m)
}
if i != -1 {
d := uint(len(b) - i - 1)
if d > decimalDigits {
return 0, fmt.Errorf("decimal digits should be less than %d, but got %d", decimalDigits, d)
}
}
return f, nil
}
func (validator *FloatValidator) String() string {
validator.SetDefaults()
rule := rules.NewRule(validator.Names()[0])
decimalDigits := *validator.DecimalDigits
rule.Params = []rules.RuleNode{
rules.NewRuleLit([]byte(strconv.Itoa(int(validator.MaxDigits)))),
rules.NewRuleLit([]byte(strconv.Itoa(int(decimalDigits)))),
}
if validator.Minimum != nil || validator.Maximum != nil {
rule.Range = make([]*rules.RuleLit, 2)
if validator.Minimum != nil {
rule.Range[0] = rules.NewRuleLit(
[]byte(fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", *validator.Minimum)),
)
}
if validator.Maximum != nil {
rule.Range[1] = rules.NewRuleLit(
[]byte(fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", *validator.Maximum)),
)
}
rule.ExclusiveLeft = validator.ExclusiveMinimum
rule.ExclusiveRight = validator.ExclusiveMaximum
}
if validator.MultipleOf != 0 {
rule.ValueMatrix = [][]*rules.RuleLit{
{rules.NewRuleLit([]byte("%" + fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", validator.MultipleOf)))},
}
} else if validator.Enums != nil {
ruleValues := make([]*rules.RuleLit, 0)
for _, str := range validator.Enums {
ruleValues = append(ruleValues, rules.NewRuleLit([]byte(str)))
}
rule.ValueMatrix = [][]*rules.RuleLit{ruleValues}
}
return string(rule.Bytes())
}