ints_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // 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. package set
  5. import (
  6. "math/rand"
  7. "testing"
  8. )
  9. const maxLimit = 1024
  10. var toSet, toClear [maxLimit]bool
  11. func init() {
  12. r := rand.New(rand.NewSource(0))
  13. for i := 0; i < maxLimit; i++ {
  14. toSet[i] = r.Intn(2) == 0
  15. toClear[i] = r.Intn(2) == 0
  16. }
  17. }
  18. func TestInts(t *testing.T) {
  19. type set interface {
  20. Len() int
  21. Has(n uint64) bool
  22. Set(n uint64)
  23. Clear(n uint64)
  24. }
  25. tests := []struct {
  26. label string
  27. makeSet func() set
  28. limit int
  29. }{
  30. {label: "Int32s", makeSet: func() set { return new(Int32s) }, limit: 32},
  31. {label: "Int64s", makeSet: func() set { return new(Int64s) }, limit: 64},
  32. {label: "Ints", makeSet: func() set { return new(Ints) }, limit: maxLimit},
  33. }
  34. for _, tt := range tests {
  35. t.Run(tt.label, func(t *testing.T) {
  36. ns := tt.makeSet()
  37. // Check that set starts empty.
  38. wantLen := 0
  39. if ns.Len() != wantLen {
  40. t.Errorf("init: Len() = %d, want %d", ns.Len(), wantLen)
  41. }
  42. for i := 0; i < tt.limit; i++ {
  43. if ns.Has(uint64(i)) {
  44. t.Errorf("init: Has(%d) = true, want false", i)
  45. }
  46. }
  47. // Set some numbers.
  48. for i, b := range toSet[:tt.limit] {
  49. if b {
  50. ns.Set(uint64(i))
  51. wantLen++
  52. }
  53. }
  54. // Check that integers were set.
  55. if ns.Len() != wantLen {
  56. t.Errorf("after Set: Len() = %d, want %d", ns.Len(), wantLen)
  57. }
  58. for i := 0; i < tt.limit; i++ {
  59. if got := ns.Has(uint64(i)); got != toSet[i] {
  60. t.Errorf("after Set: Has(%d) = %v, want %v", i, got, !got)
  61. }
  62. }
  63. // Clear some numbers.
  64. for i, b := range toClear[:tt.limit] {
  65. if b {
  66. ns.Clear(uint64(i))
  67. if toSet[i] {
  68. wantLen--
  69. }
  70. }
  71. }
  72. // Check that integers were cleared.
  73. if ns.Len() != wantLen {
  74. t.Errorf("after Clear: Len() = %d, want %d", ns.Len(), wantLen)
  75. }
  76. for i := 0; i < tt.limit; i++ {
  77. if got := ns.Has(uint64(i)); got != toSet[i] && !toClear[i] {
  78. t.Errorf("after Clear: Has(%d) = %v, want %v", i, got, !got)
  79. }
  80. }
  81. })
  82. }
  83. }