1package junk
2
3import (
4 "fmt"
5 "testing"
6)
7
8func TestBloom(t *testing.T) {
9 if err := BloomValid(3, 10); err == nil {
10 t.Fatalf("missing error for invalid bloom filter size")
11 }
12
13 _, err := NewBloom(make([]byte, 3), 10)
14 if err == nil {
15 t.Fatalf("missing error for invalid bloom filter size")
16 }
17
18 b, err := NewBloom(make([]byte, 256), 5)
19 if err != nil {
20 t.Fatalf("newbloom: %s", err)
21 }
22
23 absent := func(v string) {
24 t.Helper()
25 if b.Has(v) {
26 t.Fatalf("should be absent: %q", v)
27 }
28 }
29
30 present := func(v string) {
31 t.Helper()
32 if !b.Has(v) {
33 t.Fatalf("should be present: %q", v)
34 }
35 }
36
37 absent("test")
38 if b.Modified() {
39 t.Fatalf("bloom filter already modified?")
40 }
41 b.Add("test")
42 present("test")
43 present("test")
44 words := []string{}
45 for i := 'a'; i <= 'z'; i++ {
46 words = append(words, fmt.Sprintf("%c", i))
47 }
48 for _, w := range words {
49 absent(w)
50 b.Add(w)
51 present(w)
52 }
53 for _, w := range words {
54 present(w)
55 }
56 if !b.Modified() {
57 t.Fatalf("bloom filter was not modified?")
58 }
59
60 //log.Infof("ones: %d, m %d", b.Ones(), len(b.Bytes())*8)
61}
62
63func TestBits(t *testing.T) {
64 b := &bits{width: 1, buf: []byte{0xff, 0xff}}
65 for i := 0; i < 16; i++ {
66 if b.nextPos() != 1 {
67 t.Fatalf("pos not 1")
68 }
69 }
70 b = &bits{width: 2, buf: []byte{0xff, 0xff}}
71 for i := 0; i < 8; i++ {
72 if b.nextPos() != 0b11 {
73 t.Fatalf("pos not 0b11")
74 }
75 }
76
77 b = &bits{width: 1, buf: []byte{0b10101010, 0b10101010}}
78 for i := 0; i < 16; i++ {
79 if b.nextPos() != ((i + 1) % 2) {
80 t.Fatalf("bad pos")
81 }
82 }
83 b = &bits{width: 2, buf: []byte{0b10101010, 0b10101010}}
84 for i := 0; i < 8; i++ {
85 if b.nextPos() != 0b10 {
86 t.Fatalf("pos not 0b10")
87 }
88 }
89}
90
91func TestSet(t *testing.T) {
92 b := &Bloom{
93 data: []byte{
94 0b10101010,
95 0b00000000,
96 0b11111111,
97 0b01010101,
98 },
99 }
100 for i := 0; i < 8; i++ {
101 v := b.has(i)
102 if v != (i%2 == 0) {
103 t.Fatalf("bad has")
104 }
105 }
106 for i := 8; i < 16; i++ {
107 if b.has(i) {
108 t.Fatalf("bad has")
109 }
110 }
111 for i := 16; i < 24; i++ {
112 if !b.has(i) {
113 t.Fatalf("bad has")
114 }
115 }
116 for i := 24; i < 32; i++ {
117 v := b.has(i)
118 if v != (i%2 != 0) {
119 t.Fatalf("bad has")
120 }
121 }
122}
123
124func TestOnes(t *testing.T) {
125 ones := func(b *Bloom, x int) {
126 t.Helper()
127 n := b.Ones()
128 if n != x {
129 t.Fatalf("ones: got %d, expected %d", n, x)
130 }
131 }
132 ones(&Bloom{data: []byte{0b10101010}}, 4)
133 ones(&Bloom{data: []byte{0b01010101}}, 4)
134 ones(&Bloom{data: []byte{0b11111111}}, 8)
135 ones(&Bloom{data: []byte{0b00000000}}, 0)
136}
137