-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
85 lines (70 loc) · 1.68 KB
/
utils.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
package validator
import (
"fmt"
"strconv"
"github.com/go-courier/ptr"
"github.com/go-courier/validator/rules"
)
func MinInt(bitSize uint) int64 {
return -(1 << (bitSize - 1))
}
func MaxInt(bitSize uint) int64 {
return 1<<(bitSize-1) - 1
}
func MaxUint(bitSize uint) uint64 {
return 1<<bitSize - 1
}
func RangeFromUint(min uint64, max *uint64) []*rules.RuleLit {
ranges := make([]*rules.RuleLit, 2)
if min == 0 && max == nil {
return nil
}
ranges[0] = rules.NewRuleLit([]byte(fmt.Sprintf("%d", min)))
if max != nil {
if min == *max {
return []*rules.RuleLit{ranges[0]}
}
ranges[1] = rules.NewRuleLit([]byte(fmt.Sprintf("%d", *max)))
}
return ranges
}
func UintRange(typ string, bitSize uint, ranges ...*rules.RuleLit) (uint64, *uint64, error) {
parseUint := func(b []byte) (*uint64, error) {
if len(b) == 0 {
return nil, nil
}
n, err := strconv.ParseUint(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 := parseUint(ranges[0].Bytes())
if err != nil {
return 0, nil, fmt.Errorf("min %s", err)
}
if min == nil {
min = ptr.Uint64(0)
}
max, err := parseUint(ranges[1].Bytes())
if err != nil {
return 0, nil, fmt.Errorf("max %s", err)
}
if max != nil && *max < *min {
return 0, nil, fmt.Errorf("max %s value must be equal or large than min value %d, current %d", typ, min, max)
}
return *min, max, nil
case 1:
min, err := parseUint(ranges[0].Bytes())
if err != nil {
return 0, nil, fmt.Errorf("min %s", err)
}
if min == nil {
min = ptr.Uint64(0)
}
return *min, min, nil
}
return 0, nil, nil
}