-
Notifications
You must be signed in to change notification settings - Fork 175
/
config_struct.go
98 lines (89 loc) · 1.86 KB
/
config_struct.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
package main
import (
"errors"
"strconv"
"strings"
)
// parse int set
func ParseIntSet(str string) (*IntSet, error) {
if str == "" {
return nil, errors.New("empty str")
}
var intSet IntSet
for _, item := range strings.Split(str, ":") {
var numbers = strings.Split(item, "-")
if len(numbers) > 2 {
return nil, errors.New("illegal range str: " + item)
}
if len(numbers) == 1 {
start, err := strconv.Atoi(numbers[0])
if err != nil {
return nil, err
}
intSet.ranges = append(intSet.ranges, NewIntRange(start, start))
} else if len(numbers) == 2 {
start, err := strconv.Atoi(numbers[0])
if err != nil {
return nil, err
}
end, err := strconv.Atoi(numbers[1])
if err != nil {
return nil, err
}
intSet.ranges = append(intSet.ranges, NewIntRange(start, end))
}
}
return &intSet, nil
}
// A set of int values
type IntSet struct {
ranges []IntRange
}
// Create new IntSet
func NewIntSet(ranges ...IntRange) *IntSet {
return &IntSet{
ranges: ranges,
}
}
// implement Stringer
func (s *IntSet) String() string {
var sb strings.Builder
for index, r := range s.ranges {
if index > 0 {
sb.WriteRune(':')
}
if r.Start == r.End {
sb.WriteString(strconv.Itoa(r.Start))
} else {
sb.WriteString(strconv.Itoa(r.Start))
sb.WriteRune('-')
sb.WriteString(strconv.Itoa(r.End))
}
}
return sb.String()
}
// If this set contains int value
func (s *IntSet) Contains(value int) bool {
for _, r := range s.ranges {
if r.Contains(value) {
return true
}
}
return false
}
// Range of int value
type IntRange struct {
Start int // inclusive
End int // inclusive
}
// Create new int range
func NewIntRange(start int, end int) IntRange {
return IntRange{
Start: start,
End: end,
}
}
// If this range contains the value
func (r *IntRange) Contains(value int) bool {
return value >= r.Start && value <= r.End
}