| 1 |
package tst |
| 2 |
|
| 3 |
import ( |
| 4 |
|
| 5 |
"math/rand" |
| 6 |
"testing" |
| 7 |
) |
| 8 |
|
| 9 |
func randomString() string { |
| 10 |
n := 3 + rand.Intn(10) |
| 11 |
bs := make([]byte, n) |
| 12 |
for i := 0; i<n; i++ { |
| 13 |
bs[i] = byte(97 + rand.Intn(25)) |
| 14 |
} |
| 15 |
return string(bs) |
| 16 |
} |
| 17 |
|
| 18 |
func Test(t *testing.T) { |
| 19 |
tree := New() |
| 20 |
tree.Insert("test", 1) |
| 21 |
if tree.Len() != 1 { |
| 22 |
t.Errorf("expecting len 1") |
| 23 |
} |
| 24 |
if !tree.Has("test") { |
| 25 |
t.Errorf("expecting to find key=test") |
| 26 |
} |
| 27 |
|
| 28 |
tree.Insert("testing", 2) |
| 29 |
tree.Insert("abcd", 0) |
| 30 |
|
| 31 |
found := false |
| 32 |
tree.Do(func(key string, val interface{})bool { |
| 33 |
if key == "test" && val.(int) == 1 { |
| 34 |
found = true |
| 35 |
} |
| 36 |
return true |
| 37 |
}) |
| 38 |
if !found { |
| 39 |
t.Errorf("expecting iterator to find test") |
| 40 |
} |
| 41 |
|
| 42 |
tree.Remove("testing") |
| 43 |
tree.Remove("abcd") |
| 44 |
|
| 45 |
v := tree.Remove("test") |
| 46 |
if tree.Len() != 0 { |
| 47 |
t.Errorf("expecting len 0") |
| 48 |
} |
| 49 |
if tree.Has("test") { |
| 50 |
t.Errorf("expecting not to find key=test") |
| 51 |
} |
| 52 |
if v.(int) != 1 { |
| 53 |
t.Errorf("expecting value=1") |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
func BenchmarkInsert(b *testing.B) { |
| 58 |
b.StopTimer() |
| 59 |
strs := make([]string, b.N) |
| 60 |
for i := 0; i<b.N; i++ { |
| 61 |
strs[i] = randomString() |
| 62 |
} |
| 63 |
b.StartTimer() |
| 64 |
|
| 65 |
tree := New() |
| 66 |
for i, str := range strs { |
| 67 |
tree.Insert(str, i) |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
func BenchmarkMapInsert(b *testing.B) { |
| 72 |
b.StopTimer() |
| 73 |
strs := make([]string, b.N) |
| 74 |
for i := 0; i<b.N; i++ { |
| 75 |
strs[i] = randomString() |
| 76 |
} |
| 77 |
b.StartTimer() |
| 78 |
|
| 79 |
m := make(map[string]int) |
| 80 |
for i, str := range strs { |
| 81 |
m[str] = i |
| 82 |
} |
| 83 |
} |