blob: b370d32705d1d14ee175c263616c7c3bc2fb67cf [file] [log] [blame]
Joe Tsaid55639e2018-08-09 13:35:22 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package set
6
7import (
8 "math/rand"
9 "testing"
10)
11
12const maxLimit = 1024
13
14var toSet, toClear [maxLimit]bool
15
16func init() {
17 r := rand.New(rand.NewSource(0))
18 for i := 0; i < maxLimit; i++ {
19 toSet[i] = r.Intn(2) == 0
20 toClear[i] = r.Intn(2) == 0
21 }
22}
23
24func TestInts(t *testing.T) {
25 type set interface {
26 Len() int
27 Has(n uint64) bool
28 Set(n uint64)
29 Clear(n uint64)
30 }
31
32 tests := []struct {
33 label string
34 makeSet func() set
35 limit int
36 }{
37 {label: "Int32s", makeSet: func() set { return new(Int32s) }, limit: 32},
38 {label: "Int64s", makeSet: func() set { return new(Int64s) }, limit: 64},
39 {label: "Ints", makeSet: func() set { return new(Ints) }, limit: maxLimit},
40 }
41
42 for _, tt := range tests {
43 t.Run(tt.label, func(t *testing.T) {
44 ns := tt.makeSet()
45
46 // Check that set starts empty.
47 wantLen := 0
48 if ns.Len() != wantLen {
49 t.Errorf("init: Len() = %d, want %d", ns.Len(), wantLen)
50 }
51 for i := 0; i < tt.limit; i++ {
52 if ns.Has(uint64(i)) {
53 t.Errorf("init: Has(%d) = true, want false", i)
54 }
55 }
56
57 // Set some numbers.
58 for i, b := range toSet[:tt.limit] {
59 if b {
60 ns.Set(uint64(i))
61 wantLen++
62 }
63 }
64
65 // Check that integers were set.
66 if ns.Len() != wantLen {
67 t.Errorf("after Set: Len() = %d, want %d", ns.Len(), wantLen)
68 }
69 for i := 0; i < tt.limit; i++ {
70 if got := ns.Has(uint64(i)); got != toSet[i] {
71 t.Errorf("after Set: Has(%d) = %v, want %v", i, got, !got)
72 }
73 }
74
75 // Clear some numbers.
76 for i, b := range toClear[:tt.limit] {
77 if b {
78 ns.Clear(uint64(i))
79 if toSet[i] {
80 wantLen--
81 }
82 }
83 }
84
85 // Check that integers were cleared.
86 if ns.Len() != wantLen {
87 t.Errorf("after Clear: Len() = %d, want %d", ns.Len(), wantLen)
88 }
89 for i := 0; i < tt.limit; i++ {
90 if got := ns.Has(uint64(i)); got != toSet[i] && !toClear[i] {
91 t.Errorf("after Clear: Has(%d) = %v, want %v", i, got, !got)
92 }
93 }
94 })
95 }
96}