blob: a9a76c1791427a6617c24beb302bdfd668fa36ec [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package util
18
19// A simple trie implementation with Add and HasPrefix methods only.
20type Trie struct {
21 children map[byte]*Trie
22 wordTail bool
23 word string
24}
25
26// NewTrie creates a Trie and add all strings in the provided list to it.
27func NewTrie(list []string) Trie {
28 ret := Trie{
29 children: make(map[byte]*Trie),
30 wordTail: false,
31 }
32 for _, v := range list {
33 ret.Add(v)
34 }
35 return ret
36}
37
38// Add adds a word to this trie
39func (t *Trie) Add(v string) {
40 root := t
41 for _, b := range []byte(v) {
42 child, exists := root.children[b]
43 if !exists {
44 child = &Trie{
45 children: make(map[byte]*Trie),
46 wordTail: false,
47 }
48 root.children[b] = child
49 }
50 root = child
51 }
52 root.wordTail = true
53 root.word = v
54}
55
56// HasPrefix returns true of v has any of the prefixes stored in this trie.
57func (t *Trie) HasPrefix(v string) bool {
58 _, has := t.GetPrefix(v)
59 return has
60}
61
62// GetPrefix is like HasPrefix but return the prefix in case of match or empty string otherwise.
63func (t *Trie) GetPrefix(v string) (string, bool) {
64 root := t
65 if root.wordTail {
66 return root.word, true
67 }
68 for _, b := range []byte(v) {
69 child, exists := root.children[b]
70 if !exists {
71 return "", false
72 }
73 if child.wordTail {
74 return child.word, true
75 }
76 root = child
77 }
78 return "", false
79}