forked from naylorpmax-joyent/trie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
30 lines (26 loc) · 1.11 KB
/
common.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
package trie
import (
"strings"
)
// WalkFunc defines some action to take on the given key and value during
// a Trie Walk. Returning a non-nil error will terminate the Walk.
type WalkFunc func(key string, value interface{}) error
// StringSegmenter takes a string key with a starting index and returns
// the first segment after the start and the ending index. When the end is
// reached, the returned nextIndex should be -1.
// Implementations should NOT allocate heap memory as Trie Segmenters are
// called upon Gets. See PathSegmenter.
type StringSegmenter func(key string, start int) (segment string, nextIndex int)
// PathSegmenter segments string key paths by slash separators. For example,
// "/a/b/c" -> ("/a", 2), ("/b", 4), ("/c", -1) in successive calls. It does
// not allocate any heap memory.
func PathSegmenter(path string, start int) (segment string, next int) {
if len(path) == 0 || start < 0 || start > len(path)-1 {
return "", -1
}
end := strings.IndexRune(path[start+1:], '/') // next '/' after 0th rune
if end == -1 {
return path[start:], -1
}
return path[start : start+end+1], start + end + 1
}