-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringtable.go
45 lines (39 loc) · 1.09 KB
/
stringtable.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
package DragonBlood
// StringTable is a simple encoding interface.
// Encode() maps a string to an integer and returns ok if the string was
// already in the table. If the string was not previous known,
// Encode() still returns an integer, but returns ok == false.
// Decode(int) returns the string that maps to the passed int.
// Implementations should guarantee that Decode(Encode(string)) == string
type StringTable interface {
Encode(string) (result int, ok bool)
Decode(int) string
Len() int
}
// stringTable is an implementation of the StringTable interface
type stringTable struct {
mapper map[string]int
unmapper []string
}
// Return the canonoical StringTable implementation
func NewStringTable() *stringTable {
return &stringTable{
make(map[string]int),
nil,
}
}
func (st *stringTable) Encode(s string) (int, bool) {
m, ok := st.mapper[s]
if !ok {
m = len(st.unmapper)
st.mapper[s] = m
st.unmapper = append(st.unmapper, s)
}
return m, ok
}
func (st *stringTable) Decode(i int) string {
return st.unmapper[i]
}
func (st *stringTable) Len() int {
return len(st.unmapper)
}