Untitled

mail@pastecode.io avatar
unknown
golang
a year ago
1.0 kB
0
Indexable
Never
package bitmap

import "fmt"

//If we have n rows to judge, we design the size to be n
func New(n int) *Bitmap {
	return &Bitmap{
		Len:  n,
		Any:  false,
		Data: make([]byte, (n-1)/8+1),
	}
}

func (n *Bitmap) IsEmpty() bool {
	return !n.Any
}

//row>>3 equals row/8, row & 0x7 equals row%8
func (n *Bitmap) Add(row uint64) {
	n.Data[row>>3] |= 1 << (row & 0x7)
	n.Any = true
}

func (n *Bitmap) Del(row uint64) {
	if n.Contains(row) {
		n.Data[row>>3] &= ^(uint8(1) << (row & 0x7))
	}
	// not impleted Any = false
}

func (n *Bitmap) Contains(row uint64) bool {
	return (n.Data[row>>3] & (1 << (row & 0x7))) != 0
}

func (n *Bitmap) Filter(sels []int64) *Bitmap {
	m := New(n.Len)
	for i, sel := range sels {
		if n.Contains(uint64(sel)) {
			m.Add(uint64(i))
		}
	}
	return m
}

func (n *Bitmap) Rows() []uint64 {
	var rows []uint64

	for i, j := uint64(0), uint64(n.Len); i < j; i++ {
		if n.Contains(i) {
			rows = append(rows, i)
		}
	}
	return rows
}

func (n *Bitmap) String() string {
	return fmt.Sprintf("%v", n.Rows())
}