8 func randBitArray(bits int) (*BitArray, []byte) {
9 src := RandBytes((bits + 7) / 8)
10 bA := NewBitArray(bits)
11 for i := 0; i < len(src); i++ {
12 for j := 0; j < 8; j++ {
16 setBit := src[i]&(1<<uint(j)) > 0
17 bA.SetIndex(i*8+j, setBit)
23 func TestAnd(t *testing.T) {
25 bA1, _ := randBitArray(51)
26 bA2, _ := randBitArray(31)
30 t.Error("Expected min bits", bA3.Bits)
32 if len(bA3.Elems) != len(bA2.Elems) {
33 t.Error("Expected min elems length")
35 for i := 0; i < bA3.Bits; i++ {
36 expected := bA1.GetIndex(i) && bA2.GetIndex(i)
37 if bA3.GetIndex(i) != expected {
38 t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i))
43 func TestOr(t *testing.T) {
45 bA1, _ := randBitArray(51)
46 bA2, _ := randBitArray(31)
50 t.Error("Expected max bits")
52 if len(bA3.Elems) != len(bA1.Elems) {
53 t.Error("Expected max elems length")
55 for i := 0; i < bA3.Bits; i++ {
56 expected := bA1.GetIndex(i) || bA2.GetIndex(i)
57 if bA3.GetIndex(i) != expected {
58 t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i))
63 func TestSub1(t *testing.T) {
65 bA1, _ := randBitArray(31)
66 bA2, _ := randBitArray(51)
69 if bA3.Bits != bA1.Bits {
70 t.Error("Expected bA1 bits")
72 if len(bA3.Elems) != len(bA1.Elems) {
73 t.Error("Expected bA1 elems length")
75 for i := 0; i < bA3.Bits; i++ {
76 expected := bA1.GetIndex(i)
80 if bA3.GetIndex(i) != expected {
81 t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i))
86 func TestSub2(t *testing.T) {
88 bA1, _ := randBitArray(51)
89 bA2, _ := randBitArray(31)
92 if bA3.Bits != bA1.Bits {
93 t.Error("Expected bA1 bits")
95 if len(bA3.Elems) != len(bA1.Elems) {
96 t.Error("Expected bA1 elems length")
98 for i := 0; i < bA3.Bits; i++ {
99 expected := bA1.GetIndex(i)
100 if i < bA2.Bits && bA2.GetIndex(i) {
103 if bA3.GetIndex(i) != expected {
104 t.Error("Wrong bit from bA3")
109 func TestPickRandom(t *testing.T) {
110 for idx := 0; idx < 123; idx++ {
111 bA1 := NewBitArray(123)
112 bA1.SetIndex(idx, true)
113 index, ok := bA1.PickRandom()
115 t.Fatal("Expected to pick element but got none")
118 t.Fatalf("Expected to pick element at %v but got wrong index", idx)
123 func TestBytes(t *testing.T) {
126 check := func(bA *BitArray, bz []byte) {
127 if !bytes.Equal(bA.Bytes(), bz) {
128 panic(Fmt("Expected %X but got %X", bz, bA.Bytes()))
131 check(bA, []byte{0x01})
133 check(bA, []byte{0x09})
136 check(bA, []byte{0x00, 0x00})
138 check(bA, []byte{0x80, 0x00})
140 check(bA, []byte{0x80, 0x01})
143 check(bA, []byte{0x00, 0x00})
145 check(bA, []byte{0x80, 0x00})
147 check(bA, []byte{0x80, 0x01})
149 check(bA, []byte{0x80, 0x03})
152 func TestEmptyFull(t *testing.T) {
154 for _, n := range ns {
157 t.Fatal("Expected bit array to be empty")
159 for i := 0; i < n; i++ {
163 t.Fatal("Expected bit array to be full")