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