...
1
2
3
4
5
6
7 package stringset
8
9 import "sort"
10
11
12 type Set struct {
13
14
15 Data string
16 Index []uint16
17 }
18
19
20 func (s *Set) Elem(i int) string {
21 return s.Data[s.Index[i]:s.Index[i+1]]
22 }
23
24
25 func (s *Set) Len() int {
26 return len(s.Index) - 1
27 }
28
29
30
31 func Search(s *Set, str string) int {
32
33 n := len(s.Index) - 1
34 p := sort.Search(n, func(i int) bool {
35 return s.Elem(i) >= str
36 })
37 if p == n || str != s.Elem(p) {
38 return -1
39 }
40 return p
41 }
42
43
44 type Builder struct {
45 set Set
46 index map[string]int
47 }
48
49
50 func NewBuilder() *Builder {
51 return &Builder{
52 set: Set{
53 Index: []uint16{0},
54 },
55 index: map[string]int{},
56 }
57 }
58
59
60 func (b *Builder) Set() Set {
61 return b.set
62 }
63
64
65
66 func (b *Builder) Index(s string) int {
67 return b.index[s]
68 }
69
70
71
72 func (b *Builder) Add(ss ...string) {
73
74 for _, s := range ss {
75 if _, ok := b.index[s]; ok {
76 continue
77 }
78 b.index[s] = len(b.set.Index) - 1
79 b.set.Data += s
80 x := len(b.set.Data)
81 if x > 0xFFFF {
82 panic("Index too > 0xFFFF")
83 }
84 b.set.Index = append(b.set.Index, uint16(x))
85 }
86 }
87
View as plain text