Joe Tsai | d55639e | 2018-08-09 13:35:22 -0700 | [diff] [blame] | 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 | |
| 5 | package set |
| 6 | |
| 7 | import "math/bits" |
| 8 | |
| 9 | // Int32s represents a set of integers within the range of 0..31. |
| 10 | type Int32s uint32 |
| 11 | |
| 12 | func (bs *Int32s) Len() int { |
| 13 | return bits.OnesCount32(uint32(*bs)) |
| 14 | } |
| 15 | func (bs *Int32s) Has(n uint64) bool { |
| 16 | return uint32(*bs)&(uint32(1)<<n) > 0 |
| 17 | } |
| 18 | func (bs *Int32s) Set(n uint64) { |
| 19 | *(*uint32)(bs) |= uint32(1) << n |
| 20 | } |
| 21 | func (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. |
| 26 | type Int64s uint64 |
| 27 | |
| 28 | func (bs *Int64s) Len() int { |
| 29 | return bits.OnesCount64(uint64(*bs)) |
| 30 | } |
| 31 | func (bs *Int64s) Has(n uint64) bool { |
| 32 | return uint64(*bs)&(uint64(1)<<n) > 0 |
| 33 | } |
| 34 | func (bs *Int64s) Set(n uint64) { |
| 35 | *(*uint64)(bs) |= uint64(1) << n |
| 36 | } |
| 37 | func (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. |
| 42 | type Ints struct { |
| 43 | lo Int64s |
| 44 | hi map[uint64]struct{} |
| 45 | } |
| 46 | |
| 47 | func (bs *Ints) Len() int { |
| 48 | return bs.lo.Len() + len(bs.hi) |
| 49 | } |
| 50 | func (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 | } |
| 57 | func (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 | } |
| 67 | func (bs *Ints) Clear(n uint64) { |
| 68 | if n < 64 { |
| 69 | bs.lo.Clear(n) |
| 70 | return |
| 71 | } |
| 72 | delete(bs.hi, n) |
| 73 | } |