-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource.go
74 lines (63 loc) · 1.49 KB
/
resource.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
package fit
type resource struct {
path string
methods map[string][]ResponseHandler
prefix string
children []*resource
options *Options
max int
}
// Helper functions
func newResource() *resource {
return &resource{
path: "",
methods: make(map[string][]ResponseHandler),
children: make([]*resource, 0),
prefix: "",
options: &Options{},
}
}
func newResourceFromPath(path string) *resource {
res := newResource()
res.path = path
return res
}
func (res *resource) copy() *resource {
cop := new(resource)
*cop = *res
return cop
}
func (res *resource) addMethods(methods []string, options *Options, handlers ...ResponseHandler) {
for _, m := range methods {
if _, ok := res.methods[m]; ok {
panic("handler existed!")
}
res.methods[m] = handlers
res.options = options
}
}
func (res *resource) getIndexPosition(target byte) int {
min, max := 0, len(res.prefix)
for min < max {
mid := min + ((max - min) >> 1)
if res.prefix[mid] < target {
min = mid + 1
} else {
max = mid
}
}
return min
}
func (res *resource) insertChild(index byte, child *resource) *resource {
i := res.getIndexPosition(index)
res.prefix = res.prefix[:i] + string(index) + res.prefix[i:]
res.children = append(res.children[:i], append([]*resource{child}, res.children[i:]...)...)
return child
}
func (res *resource) getChild(index byte) *resource {
i := res.getIndexPosition(index)
if i == len(res.prefix) || res.prefix[i] != index {
return nil
}
return res.children[i]
}