-
Notifications
You must be signed in to change notification settings - Fork 2
/
int_validator.go
335 lines (283 loc) · 8.11 KB
/
int_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
package validator
import (
"bytes"
"context"
"fmt"
"reflect"
"strconv"
"unicode"
"github.com/go-courier/ptr"
"github.com/go-courier/validator/errors"
"github.com/go-courier/validator/rules"
)
var (
TargetIntValue = "int value"
)
/*
Validator for int
Rules:
ranges
@int[min,max]
@int[1,10] // value should large or equal than 1 and less or equal than 10
@int(1,10] // value should large than 1 and less or equal than 10
@int[1,10) // value should large or equal than 1
@int[1,) // value should large or equal than 1 and less than the maxinum of int32
@int[,1) // value should less than 1 and large or equal than the mininum of int32
@int // value should less or equal than maxinum of int32 and large or equal than the mininum of int32
enumeration
@int{1,2,3} // should one of these values
multiple of some int value
@int{%multipleOf}
@int{%2} // should be multiple of 2
bit size in parameter
@int<8>
@int<16>
@int<32>
@int<64>
composes
@int<8>[1,]
aliases:
@int8 = @int<8>
@int16 = @int<16>
@int32 = @int<32>
@int64 = @int<64>
Tips:
for JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER
int<53>
*/
type IntValidator struct {
BitSize uint
Minimum *int64
Maximum *int64
MultipleOf int64
ExclusiveMaximum bool
ExclusiveMinimum bool
Enums map[int64]string
}
func init() {
ValidatorMgrDefault.Register(&IntValidator{})
}
func (IntValidator) Names() []string {
return []string{"int", "int8", "int16", "int32", "int64"}
}
func (validator *IntValidator) SetDefaults() {
if validator != nil {
if validator.BitSize == 0 {
validator.BitSize = 32
}
if validator.Maximum == nil {
validator.Maximum = ptr.Int64(MaxInt(validator.BitSize))
}
if validator.Minimum == nil {
validator.Minimum = ptr.Int64(MinInt(validator.BitSize))
}
}
}
func isIntType(typ reflect.Type) bool {
switch typ.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return true
}
return false
}
func (validator *IntValidator) Validate(v interface{}) error {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
if !isIntType(rv.Type()) {
return errors.NewUnsupportedTypeError(rv.Type().String(), validator.String())
}
val := rv.Int()
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: TargetIntValue,
Current: val,
Enums: values,
}
}
return nil
}
mininum := *validator.Minimum
maxinum := *validator.Maximum
if ((validator.ExclusiveMinimum && val == mininum) || val < mininum) ||
((validator.ExclusiveMaximum && val == maxinum) || val > maxinum) {
return &errors.OutOfRangeError{
Target: TargetFloatValue,
Current: val,
Minimum: mininum,
ExclusiveMinimum: validator.ExclusiveMinimum,
Maximum: maxinum,
ExclusiveMaximum: validator.ExclusiveMaximum,
}
}
if validator.MultipleOf != 0 {
if val%validator.MultipleOf != 0 {
return &errors.MultipleOfError{
Target: TargetFloatValue,
Current: val,
MultipleOf: validator.MultipleOf,
}
}
}
return nil
}
func (IntValidator) New(ctx context.Context, rule *Rule) (Validator, error) {
validator := &IntValidator{}
bitSizeBuf := &bytes.Buffer{}
for _, char := range rule.Name {
if unicode.IsDigit(char) {
bitSizeBuf.WriteRune(char)
}
}
if bitSizeBuf.Len() == 0 && rule.Params != nil {
if len(rule.Params) != 1 {
return nil, fmt.Errorf("int should only 1 parameter, but got %d", len(rule.Params))
}
bitSizeBuf.Write(rule.Params[0].Bytes())
}
if bitSizeBuf.Len() != 0 {
bitSizeStr := bitSizeBuf.String()
bitSizeNum, err := strconv.ParseUint(bitSizeStr, 10, 8)
if err != nil || bitSizeNum > 64 {
return nil, errors.NewSyntaxError("int parameter should be valid bit size, but got `%s`", bitSizeStr)
}
validator.BitSize = uint(bitSizeNum)
}
if validator.BitSize == 0 {
validator.BitSize = 32
}
if rule.Range != nil {
min, max, err := intRange(fmt.Sprintf("int<%d>", validator.BitSize), validator.BitSize, rule.Range...)
if err != nil {
return nil, err
}
validator.Minimum = min
validator.Maximum = max
validator.ExclusiveMinimum = rule.ExclusiveLeft
validator.ExclusiveMaximum = rule.ExclusiveRight
}
validator.SetDefaults()
ruleValues := rule.ComputedValues()
if ruleValues != nil {
if len(ruleValues) == 1 {
mayBeMultipleOf := ruleValues[0].Bytes()
if mayBeMultipleOf[0] == '%' {
v := mayBeMultipleOf[1:]
multipleOf, err := strconv.ParseInt(string(v), 10, int(validator.BitSize))
if err != nil {
return nil, errors.NewSyntaxError("multipleOf should be a valid int%d value, but got `%s`", validator.BitSize, v)
}
validator.MultipleOf = multipleOf
}
}
if validator.MultipleOf == 0 {
validator.Enums = map[int64]string{}
for _, v := range ruleValues {
str := string(v.Bytes())
enumValue, err := strconv.ParseInt(str, 10, int(validator.BitSize))
if err != nil {
return nil, errors.NewSyntaxError("enum should be a valid int%d value, but got `%s`", validator.BitSize, v)
}
validator.Enums[enumValue] = str
}
}
}
return validator, validator.TypeCheck(rule)
}
func (validator *IntValidator) TypeCheck(rule *Rule) error {
switch rule.Type.Kind() {
case reflect.Int8:
if validator.BitSize > 8 {
return fmt.Errorf("bit size too large for type %s", rule.Type)
}
return nil
case reflect.Int16:
if validator.BitSize > 16 {
return fmt.Errorf("bit size too large for type %s", rule.Type)
}
return nil
case reflect.Int, reflect.Int32:
if validator.BitSize > 32 {
return fmt.Errorf("bit size too large for type %s", rule.Type)
}
return nil
case reflect.Int64:
return nil
}
return errors.NewUnsupportedTypeError(rule.String(), validator.String())
}
func intRange(typ string, bitSize uint, ranges ...*rules.RuleLit) (*int64, *int64, error) {
parseInt := func(b []byte) (*int64, error) {
if len(b) == 0 {
return nil, nil
}
n, err := strconv.ParseInt(string(b), 10, int(bitSize))
if err != nil {
return nil, fmt.Errorf("%s value is not correct: %s", typ, err)
}
return &n, nil
}
switch len(ranges) {
case 2:
min, err := parseInt(ranges[0].Bytes())
if err != nil {
return nil, nil, fmt.Errorf("min %s", err)
}
max, err := parseInt(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 expect %d, current %d", typ, min, max)
}
return min, max, nil
case 1:
min, err := parseInt(ranges[0].Bytes())
if err != nil {
return nil, nil, fmt.Errorf("min %s", err)
}
return min, min, nil
}
return nil, nil, nil
}
func (validator *IntValidator) String() string {
rule := rules.NewRule(validator.Names()[0])
rule.Params = []rules.RuleNode{
rules.NewRuleLit([]byte(strconv.Itoa(int(validator.BitSize)))),
}
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("%d", *validator.Minimum)),
)
}
if validator.Maximum != nil {
rule.Range[1] = rules.NewRuleLit(
[]byte(fmt.Sprintf("%d", *validator.Maximum)),
)
}
rule.ExclusiveLeft = validator.ExclusiveMinimum
rule.ExclusiveRight = validator.ExclusiveMaximum
}
rule.ExclusiveLeft = validator.ExclusiveMinimum
rule.ExclusiveRight = validator.ExclusiveMaximum
if validator.MultipleOf != 0 {
rule.ValueMatrix = [][]*rules.RuleLit{{
rules.NewRuleLit([]byte("%" + fmt.Sprintf("%d", 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())
}