/
trie_test.go
103 lines (84 loc) · 1.93 KB
/
trie_test.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package immut
import (
"testing"
"github.com/eliothedeman/randutil"
. "github.com/smartystreets/goconvey/convey"
)
func TestTriePutGet(t *testing.T) {
x := NewTrie()
y := x.Put([]byte("hello"), "world")
if _, found := x.Get([]byte("hello")); found {
t.Error("Persistance broken. Hello should not have been found")
}
if out, found := y.Get([]byte("hello")); !found || out.(string) != "world" {
t.Fail()
}
}
func TestMassInsert(t *testing.T) {
x := NewTrie()
x = x.Put([]byte("hello"), "world")
for i := 0; i < 10000; i++ {
x = x.Put(randutil.Bytes(10), 10)
}
if y, _ := x.Get([]byte("hello")); y != "world" {
t.Fail()
}
}
func TestTrieDel(t *testing.T) {
Convey("Ensure deleting keys from one trie doesn't effect the previous generation", t, func() {
x := NewTrie()
x = x.Put([]byte("hello"), "world")
y, i := x.Del([]byte("hello"))
So(i, ShouldEqual, "world")
keys := x.Keys()
for _, k := range keys {
So("hello", ShouldEqual, string(k))
}
keys = y.Keys()
for _, k := range keys {
So("hello", ShouldNotEqual, string(k))
}
})
}
func randStrs(count int) []string {
b := make([]string, count)
for i := 0; i < count; i++ {
b[i] = randutil.AlphaString(randutil.IntRange(10, 20))
}
return b
}
func randBytes(count int) [][]byte {
b := make([][]byte, count)
x := randStrs(count)
for i := 0; i < count; i++ {
b[i] = []byte(x[i])
}
return b
}
func BenchmarkTriePut(b *testing.B) {
strs := randBytes(1000)
x := NewTrie()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
x = x.Put(strs[i%len(strs)], randutil.Int())
}
}
func BenchmarkTriePutSingle(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
x := NewTrie()
s := []byte("hell world")
for i := 0; i < b.N; i++ {
x = x.Put(s, i)
}
}
func BenchmarkHashPut(b *testing.B) {
strs := randStrs(1000)
x := make(map[string]int)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
x[strs[i%len(strs)]] = randutil.Int()
}
}