github.com/lrita/numa@v1.0.2/bitmask.go (about)

     1  package numa
     2  
     3  import (
     4  	"fmt"
     5  	"math/bits"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  // Bitmask is used for syscall or other operation in NUMA API.
    11  type Bitmask []uint64
    12  
    13  // Set sets the No.i bit to v.
    14  func (b Bitmask) Set(i int, v bool) {
    15  	if n := i / 64; n < len(b) {
    16  		if v {
    17  			b[n] |= uint64(1) << uint64(i%64)
    18  		} else {
    19  			b[n] &= ^(uint64(1) << uint64(i%64))
    20  		}
    21  	}
    22  }
    23  
    24  // Get returns the No.i bit of this bitmask.
    25  func (b Bitmask) Get(i int) bool {
    26  	if n := i / 64; n < len(b) {
    27  		return (b[n]>>uint64(i%64))&0x1 != 0
    28  	}
    29  	return false
    30  }
    31  
    32  // ClearAll clear all bits of this bitmask.
    33  func (b Bitmask) ClearAll() {
    34  	for i := range b {
    35  		b[i] = 0
    36  	}
    37  }
    38  
    39  // SetAll clear all bits of this bitmask.
    40  func (b Bitmask) SetAll() {
    41  	for i := range b {
    42  		b[i] = ^uint64(0)
    43  	}
    44  }
    45  
    46  // OnesCount returns the number of one bits ("population count") in this bitmask.
    47  func (b Bitmask) OnesCount() (n int) {
    48  	for _, v := range b {
    49  		n += bits.OnesCount64(v)
    50  	}
    51  	return
    52  }
    53  
    54  // String returns the hex string of this bitmask.
    55  func (b Bitmask) String() string {
    56  	s := make([]string, 0, len(b))
    57  	for _, v := range b {
    58  		s = append(s, fmt.Sprintf("%016X", v))
    59  	}
    60  	return strings.Join(s, ",")
    61  }
    62  
    63  // Text returns the digital bit text of this bitmask.
    64  func (b Bitmask) Text() string {
    65  	var (
    66  		s   []string
    67  		len = b.Len() * 8
    68  	)
    69  	for i := 0; i < len; i++ {
    70  		if b.Get(i) {
    71  			s = append(s, strconv.Itoa(i))
    72  		}
    73  	}
    74  	return strings.Join(s, ",")
    75  }
    76  
    77  // Len returns the bitmask length.
    78  func (b Bitmask) Len() int { return len(b) * 64 }
    79  
    80  // Clone return a duplicated bitmask.
    81  func (b Bitmask) Clone() Bitmask {
    82  	bb := make(Bitmask, len(b))
    83  	copy(bb, b)
    84  	return bb
    85  }
    86  
    87  // NewBitmask returns a bitmask, which length always rounded to a multiple of
    88  // sizeof(uint64). The input param n represents the bit count of this bitmask.
    89  func NewBitmask(n int) Bitmask {
    90  	return make(Bitmask, (n+63)/64)
    91  }