ints.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 "math/bits"
  6. // Int32s represents a set of integers within the range of 0..31.
  7. type Int32s uint32
  8. func (bs *Int32s) Len() int {
  9. return bits.OnesCount32(uint32(*bs))
  10. }
  11. func (bs *Int32s) Has(n uint64) bool {
  12. return uint32(*bs)&(uint32(1)<<n) > 0
  13. }
  14. func (bs *Int32s) Set(n uint64) {
  15. *(*uint32)(bs) |= uint32(1) << n
  16. }
  17. func (bs *Int32s) Clear(n uint64) {
  18. *(*uint32)(bs) &^= uint32(1) << n
  19. }
  20. // Int64s represents a set of integers within the range of 0..63.
  21. type Int64s uint64
  22. func (bs *Int64s) Len() int {
  23. return bits.OnesCount64(uint64(*bs))
  24. }
  25. func (bs *Int64s) Has(n uint64) bool {
  26. return uint64(*bs)&(uint64(1)<<n) > 0
  27. }
  28. func (bs *Int64s) Set(n uint64) {
  29. *(*uint64)(bs) |= uint64(1) << n
  30. }
  31. func (bs *Int64s) Clear(n uint64) {
  32. *(*uint64)(bs) &^= uint64(1) << n
  33. }
  34. // Ints represents a set of integers within the range of 0..math.MaxUint64.
  35. type Ints struct {
  36. lo Int64s
  37. hi map[uint64]struct{}
  38. }
  39. func (bs *Ints) Len() int {
  40. return bs.lo.Len() + len(bs.hi)
  41. }
  42. func (bs *Ints) Has(n uint64) bool {
  43. if n < 64 {
  44. return bs.lo.Has(n)
  45. }
  46. _, ok := bs.hi[n]
  47. return ok
  48. }
  49. func (bs *Ints) Set(n uint64) {
  50. if n < 64 {
  51. bs.lo.Set(n)
  52. return
  53. }
  54. if bs.hi == nil {
  55. bs.hi = make(map[uint64]struct{})
  56. }
  57. bs.hi[n] = struct{}{}
  58. }
  59. func (bs *Ints) Clear(n uint64) {
  60. if n < 64 {
  61. bs.lo.Clear(n)
  62. return
  63. }
  64. delete(bs.hi, n)
  65. }