github.com/wzzhu/tensor@v0.9.24/bitmap.go (about)

     1  package tensor
     2  
     3  // BitMap is a very simple bitmap. It only supports Set, IsSet and Clear methods. It's mostly used for tracking which element has been set
     4  type BitMap struct {
     5  	n   []uint64
     6  	max int
     7  }
     8  
     9  // NewBitMap creates a new BitMap.
    10  func NewBitMap(size int) *BitMap {
    11  	q, r := divmod(size, 64)
    12  
    13  	if r > 0 {
    14  		q++
    15  	}
    16  
    17  	return &BitMap{
    18  		n:   make([]uint64, q),
    19  		max: size,
    20  	}
    21  }
    22  
    23  // Set sets the ith bit of the bit map to 1. It panics if i is greater or equal to the defined max
    24  func (bm *BitMap) Set(i int) {
    25  	if i >= bm.max || i < 0 {
    26  		panic("Index out of range")
    27  	}
    28  
    29  	block, pos := divmod(i, 64)
    30  	bm.n[block] |= uint64(1) << uint64(pos)
    31  }
    32  
    33  // IsSet returns true if the ith bit is set. It panics if the i is greater or equal to the defined max
    34  func (bm *BitMap) IsSet(i int) bool {
    35  	if i >= bm.max || i < 0 {
    36  		panic("Index out of range")
    37  	}
    38  
    39  	block, pos := divmod(i, 64)
    40  	return bm.n[block]>>uint64(pos)&uint64(1) == uint64(1)
    41  }
    42  
    43  // Clear clears the ith bit. It panics if i is greater or equal to the defined max
    44  func (bm *BitMap) Clear(i int) {
    45  	if i >= bm.max || i < 0 {
    46  		panic("Index out of range")
    47  	}
    48  
    49  	block, pos := divmod(i, 64)
    50  	bm.n[block] &= ^(uint64(1) << uint64(pos))
    51  }