| 1 | package trie |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | ) |
| 6 | |
| 7 | // WalkFunc defines some action to take on the given key and value during |
| 8 | // a Trie Walk. Returning a non-nil error will terminate the Walk. |
| 9 | type WalkFunc func(key string, value interface{}) error |
| 10 | |
| 11 | // StringSegmenter takes a string key with a starting index and returns |
| 12 | // the first segment after the start and the ending index. When the end is |
| 13 | // reached, the returned nextIndex should be -1. |
| 14 | // Implementations should NOT allocate heap memory as Trie Segmenters are |
| 15 | // called upon Gets. See PathSegmenter. |
| 16 | type StringSegmenter func(key string, start int) (segment string, nextIndex int) |
| 17 | |
| 18 | // PathSegmenter segments string key paths by slash separators. For example, |
| 19 | // "/a/b/c" -> ("/a", 2), ("/b", 4), ("/c", -1) in successive calls. It does |
| 20 | // not allocate any heap memory. |
| 21 | func PathSegmenter(path string, start int) (segment string, next int) { |
| 22 | if len(path) == 0 || start < 0 || start > len(path)-1 { |
| 23 | return "", -1 |
| 24 | } |
| 25 | end := strings.IndexRune(path[start+1:], '/') // next '/' after 0th rune |
| 26 | if end == -1 { |
| 27 | return path[start:], -1 |
| 28 | } |
| 29 | return path[start : start+end+1], start + end + 1 |
| 30 | } |