Involved Source Files Package bitset implements bitsets, a mapping
between non-negative integers and boolean values. It should be more
efficient than map[uint] bool.
It provides methods for setting, clearing, flipping, and testing
individual integers.
But it also provides set intersection, union, difference,
complement, and symmetric operations, as well as tests to
check whether any, all, or no bits are set, and querying a
bitset's current length and number of positive bits.
BitSets are expanded to the size of the largest set bit; the
memory allocation is approximately Max bits, where Max is
the largest set bit. BitSets are never shrunk. On creation,
a hint can be given for the number of bits that will be used.
Many of the methods, including Set,Clear, and Flip, return
a BitSet pointer, which allows for chaining.
Example use:
import "bitset"
var b BitSet
b.Set(10).Set(11)
if b.Test(1000) {
b.Clear(1000)
}
if B.Intersection(bitset.New(100).Set(10)).Count() > 1 {
fmt.Println("Intersection works.")
}
As an alternative to BitSets, one should check out the 'big' package,
which provides a (less set-theoretical) view of bitsets.bitset_iter.gopext.gen.gopopcnt.goselect.go
Package-Level Type Names (total 2)
/* sort by: | */
A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. All returns true if all bits are set, false otherwise. Returns true for
empty sets. Any returns true if any bit is set, false otherwise AppendTo appends all set bits to buf and returns the (maybe extended) buf.
In case of allocation failure, the function will panic.
See also [BitSet.AsSlice] and [BitSet.NextSetMany]. AsSlice returns all set bits as slice.
It panics if the capacity of buf is < b.Count()
See also [BitSet.AppendTo] and [BitSet.NextSetMany]. BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation.
It is not a copy, so changes to the returned slice will affect the bitset.
It is meant for advanced users.
Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. Clear bit i to 0. This never cause a memory allocation. It is always safe. ClearAll clears the entire BitSet.
It does not free the memory. Clone this BitSet, returning a new BitSet that has the same bits set.
In case of allocation failure, the function will return an empty BitSet. Compact shrinks BitSet to so that we preserve all set bits, while minimizing
memory usage. Compact calls Shrink.
A new slice is allocated to store the new bits, so you may see an increase in
memory usage until the GC runs. Normally this should not be a problem, but if you
have an extremely large BitSet its important to understand that the old BitSet will
remain in memory until the GC frees it.
If you are memory constrained, this function may cause a panic. Complement computes the (local) complement of a bitset (up to length bits)
In case of allocation failure, the function will return an empty BitSet. Copy into a destination BitSet using the Go array copy semantics:
the number of bits copied is the minimum of the number of bits in the current
BitSet (Len()) and the destination Bitset.
We return the number of bits copied in the destination BitSet. CopyFull copies into a destination BitSet such that the destination is
identical to the source after the operation, allocating memory if necessary. Count (number of set bits).
Also known as "popcount" or "population count". DeleteAt deletes the bit at the given index position from
within the bitset
All the bits residing on the left of the deleted bit get
shifted right by 1
The running time of this operation may potentially be
relatively slow, O(length) Deposit creates a new BitSet and deposits bits according to a mask.
See DepositTo for details. DepositTo spreads bits from a compacted form in the BitSet into positions
specified by mask in dst. This is the inverse operation of Extract.
For example, if mask has bits set at positions 1,4,5, then DepositTo will
take consecutive bits 0,1,2 from the source BitSet and place them into
positions 1,4,5 in the destination BitSet. Difference of base set and other set
This is the BitSet equivalent of &^ (and not) DifferenceCardinality computes the cardinality of the difference DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go,
the least significant bits are printed last (index 0 is at the end of the string).
This is useful for debugging and testing. It is not suitable for serialization.(*BitSet) EachSet() iter.Seq[uint] Equal tests the equivalence of two BitSets.
False if they are of different sizes, otherwise true
only if all the same bits are set Extract extracts bits according to a mask and returns the result
in a new BitSet. See ExtractTo for details. ExtractTo copies bits from the BitSet using positions specified in mask
into a compacted form in dst. The number of set bits in mask determines
the number of bits that will be extracted.
For example, if mask has bits set at positions 1,4,5, then ExtractTo will
take bits at those positions from the source BitSet and pack them into
consecutive positions 0,1,2 in the destination BitSet. Flip bit at i.
Warning: using a very large value for 'i'
may lead to a memory shortage and a panic: the caller is responsible
for providing sensible parameters in line with their memory capacity. FlipRange bit in [start, end).
Warning: using a very large value for 'end'
may lead to a memory shortage and a panic: the caller is responsible
for providing sensible parameters in line with their memory capacity. GetWord64AtBit retrieves bits i through i+63 as a single uint64 value InPlaceDifference computes the difference of base set and other set
This is the BitSet equivalent of &^ (and not) InPlaceIntersection destructively computes the intersection of
base set and the compare set.
This is the BitSet equivalent of & (and) InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set
This is the BitSet equivalent of ^ (xor) InPlaceUnion creates the destructive union of base set and compare set.
This is the BitSet equivalent of | (or). InsertAt takes an index which indicates where a bit should be
inserted. Then it shifts all the bits in the set to the left by 1, starting
from the given index position, and sets the index position to 0.
Depending on the size of your BitSet, and where you are inserting the new entry,
this method could be extremely slow and in some cases might cause the entire BitSet
to be recopied. Intersection of base set and other set
This is the BitSet equivalent of & (and)
In case of allocation failure, the function will return an empty BitSet. IntersectionCardinality computes the cardinality of the intersection IsStrictSuperSet returns true if this is a strict superset of the other set IsSuperSet returns true if this is a superset of the other set Len returns the number of bits in the BitSet.
Note that it differ from Count function. MarshalBinary encodes a BitSet into a binary form and returns the result.
Please see WriteTo for details. MarshalJSON marshals a BitSet as a JSON structure NextClear returns the next clear bit from the specified index,
including possibly the current index
along with an error code (true = valid, false = no bit found i.e. all bits are set) NextSet returns the next bit set from the specified index,
including possibly the current index
along with an error code (true = valid, false = no set bit found)
for i,e := v.NextSet(0); e; i,e = v.NextSet(i + 1) {...}
Users concerned with performance may want to use NextSetMany to
retrieve several values at once. NextSetMany returns many next bit sets from the specified index,
including possibly the current index and up to cap(buffer).
If the returned slice has len zero, then no more set bits were found
buffer := make([]uint, 256) // this should be reused
j := uint(0)
j, buffer = bitmap.NextSetMany(j, buffer)
for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j,buffer) {
for k := range buffer {
do something with buffer[k]
}
j += 1
}
It is possible to retrieve all set bits as follow:
indices := make([]uint, bitmap.Count())
bitmap.NextSetMany(0, indices)
It is also possible to retrieve all set bits with [BitSet.AppendTo]
or [BitSet.AsSlice].
However if Count() is large, it might be preferable to
use several calls to NextSetMany for memory reasons. None returns true if no bit is set, false otherwise. Returns true for
empty sets. OnesBetween returns the number of set bits in the range [from, to).
The range is inclusive of 'from' and exclusive of 'to'.
Returns 0 if from >= to. PreviousClear returns the previous clear bit from the specified index,
including possibly the current index
along with an error code (true = valid, false = no clear bit found i.e. all bits are set) PreviousSet returns the previous set bit from the specified index,
including possibly the current index
along with an error code (true = valid, false = no bit found i.e. all bits are clear) Rank returns the number of set bits up to and including the index
that are set in the bitset.
See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics ReadFrom reads a BitSet from a stream written using WriteTo
The format is:
1. uint64 length
2. []uint64 set
See WriteTo for details.
Upon success, the number of bytes read is returned.
If the current BitSet is not large enough to hold the data,
it is extended. In case of error, the BitSet is either
left unchanged or made empty if the error occurs too late
to preserve the content.
Performance: if this function is used to read from a disk or network
connection, it might be beneficial to wrap the stream in a bufio.Reader.
E.g.,
f, err := os.Open("myfile")
r := bufio.NewReader(f) Select returns the index of the jth set bit, where j is the argument.
The caller is responsible to ensure that 0 <= j < Count(): when j is
out of range, the function returns the length of the bitset (b.length).
Note that this function differs in convention from the Rank function which
returns 1 when ranking the smallest value. We follow the conventional
textbook definition of Select and Rank. Set bit i to 1, the capacity of the bitset is automatically
increased accordingly.
Warning: using a very large value for 'i'
may lead to a memory shortage and a panic: the caller is responsible
for providing sensible parameters in line with their memory capacity.
The memory usage is at least slightly over i/8 bytes. SetAll sets the entire BitSet SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance SetTo sets bit i to value.
Warning: using a very large value for 'i'
may lead to a memory shortage and a panic: the caller is responsible
for providing sensible parameters in line with their memory capacity. ShiftLeft shifts the bitset like << operation would do.
Left shift may require bitset size extension. We try to avoid the
unnecessary memory operations by detecting the leftmost set bit.
The function will panic if shift causes excess of capacity. ShiftRight shifts the bitset like >> operation would do. Shrink shrinks BitSet so that the provided value is the last possible
set value. It clears all bits > the provided index and reduces the size
and length of the set.
Note that the parameter value is not the new length in bits: it is the
maximal value that can be stored in the bitset after the function call.
The new length in bits is the parameter value + 1. Thus it is not possible
to use this function to set the length to 0, the minimal value of the length
after this function call is 1.
A new slice is allocated to store the new bits, so you may see an increase in
memory usage until the GC runs. Normally this should not be a problem, but if you
have an extremely large BitSet its important to understand that the old BitSet will
remain in memory until the GC frees it.
If you are memory constrained, this function may cause a panic. String creates a string representation of the BitSet. It is only intended for
human-readable output and not for serialization. SymmetricDifference of base set and other set
This is the BitSet equivalent of ^ (xor) SymmetricDifferenceCardinality computes the cardinality of the symmetric difference Test whether bit i is set. Union of base set and other set
This is the BitSet equivalent of | (or) UnionCardinality computes the cardinality of the uniton of the base set
and the compare set. UnmarshalBinary decodes the binary form generated by MarshalBinary.
Please see WriteTo for details. UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON Words returns the bitset as array of 64-bit words, giving direct access to the internal representation.
It is not a copy, so changes to the returned slice will affect the bitset.
It is meant for advanced users. WriteTo writes a BitSet to a stream. The format is:
1. uint64 length
2. []uint64 set
The length is the number of bits in the BitSet.
The set is a slice of uint64s containing between length and length + 63 bits.
It is interpreted as a big-endian array of uint64s by default (see BinaryOrder())
meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored
at byte index 6... the bits 64 to 71 are stored at byte index 8, etc.
If you change the binary order, you need to do so for both reading and writing.
We recommend using the default binary order.
Upon success, the number of bytes written is returned.
Performance: if this function is used to write to a disk or network
connection, it might be beneficial to wrap the stream in a bufio.Writer.
E.g.,
f, err := os.Create("myfile")
w := bufio.NewWriter(f)
BitSet : github.com/goccy/go-json.Marshaler
*BitSet : github.com/goccy/go-json.Unmarshaler
*BitSet : encoding.BinaryMarshaler
*BitSet : encoding.BinaryUnmarshaler
BitSet : encoding/json/v2.Marshaler
*BitSet : encoding/json/v2.Unmarshaler
*BitSet : expvar.Var
*BitSet : fmt.Stringer
*BitSet : io.ReaderFrom
*BitSet : io.WriterTo
func From(buf []uint64) *BitSet
func FromWithLength(length uint, set []uint64) *BitSet
func MustNew(length uint) (bset *BitSet)
func New(length uint) (bset *BitSet)
func (*BitSet).Clear(i uint) *BitSet
func (*BitSet).ClearAll() *BitSet
func (*BitSet).Clone() *BitSet
func (*BitSet).Compact() *BitSet
func (*BitSet).Complement() (result *BitSet)
func (*BitSet).DeleteAt(i uint) *BitSet
func (*BitSet).Deposit(mask *BitSet) *BitSet
func (*BitSet).Difference(compare *BitSet) (result *BitSet)
func (*BitSet).Extract(mask *BitSet) *BitSet
func (*BitSet).Flip(i uint) *BitSet
func (*BitSet).FlipRange(start, end uint) *BitSet
func (*BitSet).InsertAt(idx uint) *BitSet
func (*BitSet).Intersection(compare *BitSet) (result *BitSet)
func (*BitSet).Set(i uint) *BitSet
func (*BitSet).SetAll() *BitSet
func (*BitSet).SetTo(i uint, value bool) *BitSet
func (*BitSet).Shrink(lastbitindex uint) *BitSet
func (*BitSet).SymmetricDifference(compare *BitSet) (result *BitSet)
func (*BitSet).Union(compare *BitSet) (result *BitSet)
func github.com/RoaringBitmap/roaring.(*Bitmap).ToBitSet() *BitSet
func github.com/RoaringBitmap/roaring/v2.(*Bitmap).ToBitSet() *BitSet
func (*BitSet).Copy(c *BitSet) (count uint)
func (*BitSet).CopyFull(c *BitSet)
func (*BitSet).Deposit(mask *BitSet) *BitSet
func (*BitSet).DepositTo(mask *BitSet, dst *BitSet)
func (*BitSet).DepositTo(mask *BitSet, dst *BitSet)
func (*BitSet).Difference(compare *BitSet) (result *BitSet)
func (*BitSet).DifferenceCardinality(compare *BitSet) uint
func (*BitSet).Equal(c *BitSet) bool
func (*BitSet).Extract(mask *BitSet) *BitSet
func (*BitSet).ExtractTo(mask *BitSet, dst *BitSet)
func (*BitSet).ExtractTo(mask *BitSet, dst *BitSet)
func (*BitSet).InPlaceDifference(compare *BitSet)
func (*BitSet).InPlaceIntersection(compare *BitSet)
func (*BitSet).InPlaceSymmetricDifference(compare *BitSet)
func (*BitSet).InPlaceUnion(compare *BitSet)
func (*BitSet).Intersection(compare *BitSet) (result *BitSet)
func (*BitSet).IntersectionCardinality(compare *BitSet) uint
func (*BitSet).IsStrictSuperSet(other *BitSet) bool
func (*BitSet).IsSuperSet(other *BitSet) bool
func (*BitSet).SymmetricDifference(compare *BitSet) (result *BitSet)
func (*BitSet).SymmetricDifferenceCardinality(compare *BitSet) uint
func (*BitSet).Union(compare *BitSet) (result *BitSet)
func (*BitSet).UnionCardinality(compare *BitSet) uint
func github.com/RoaringBitmap/roaring.FromBitSet(bitset *BitSet) *roaring.Bitmap
func github.com/RoaringBitmap/roaring/v2.FromBitSet(bitset *BitSet) *roaring.Bitmap
Error is used to distinguish errors (panics) generated in this package.
Package-Level Functions (total 9)
Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding)
BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian)
BinaryOrder returns the current binary order, see also LittleEndian()
and BigEndian() to change the order.
Cap returns the total possible capacity, or number of bits
that can be stored in the BitSet theoretically. Under 32-bit system,
it is 4294967295 and under 64-bit system, it is 18446744073709551615.
Note that this is further limited by the maximum allocation size in Go,
and your available memory, as any Go data structure.
From is a constructor used to create a BitSet from an array of words
FromWithLength constructs from an array of words and length in bits.
This function is for advanced users, most users should prefer
the From function.
As a user of FromWithLength, you are responsible for ensuring
that the length is correct: your slice should have length at
least (length+63)/64 in 64-bit words.
LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian)
MustNew creates a new BitSet with the given length bits.
It panics if length exceeds the possible capacity or by a lack of memory.
New creates a new BitSet with a hint that length bits will be required.
The memory usage is at least length/8 bytes.
In case of allocation failure, the function will return a BitSet with zero
capacity.
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.