bitmask.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright © 2021 Jeffrey H. Johnson <trnsz@pobox.com>.
  2. // Copyright © 2021 Gridfinity, LLC.
  3. // Copyright © 2019 Neal.
  4. // Copyright © 2018 lrita@163.com.
  5. //
  6. // Use of this source code is governed by the MIT
  7. // license that can be found in the LICENSE file.
  8. package gonuma
  9. import (
  10. "fmt"
  11. "math/bits"
  12. "strconv"
  13. "strings"
  14. )
  15. // Bitmask is used for syscall or other operation in NUMA API.
  16. type Bitmask []uint64
  17. // Set sets the No.i bit to v.
  18. func (b Bitmask) Set(i int, v bool) {
  19. if n := i / 64; n < len(b) {
  20. if v {
  21. b[n] |= uint64(1) << uint64(i%64)
  22. } else {
  23. b[n] &= ^(uint64(1) << uint64(i%64))
  24. }
  25. }
  26. }
  27. // Get returns the No.i bit of this bitmask.
  28. func (b Bitmask) Get(i int) bool {
  29. if n := i / 64; n < len(b) {
  30. return (b[n]>>uint64(i%64))&0x1 != 0
  31. }
  32. return false
  33. }
  34. // ClearAll clear all bits of this bitmask.
  35. func (b Bitmask) ClearAll() {
  36. for i := range b {
  37. b[i] = 0
  38. }
  39. }
  40. // SetAll clear all bits of this bitmask.
  41. func (b Bitmask) SetAll() {
  42. for i := range b {
  43. b[i] = ^uint64(0)
  44. }
  45. }
  46. // OnesCount returns the number of one bits ("population count") in this
  47. // bitmask.
  48. func (b Bitmask) OnesCount() (n int) {
  49. for _, v := range b {
  50. n += bits.OnesCount64(v)
  51. }
  52. return
  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. // Text returns the digital bit text of this bitmask.
  63. func (b Bitmask) Text() string {
  64. var (
  65. s []string
  66. length = b.Len() * 8
  67. )
  68. for i := 0; i < length; i++ {
  69. if b.Get(i) {
  70. s = append(s, strconv.Itoa(i))
  71. }
  72. }
  73. return strings.Join(s, ",")
  74. }
  75. // Len returns the bitmask length.
  76. func (b Bitmask) Len() int { return len(b) * 64 }
  77. // Clone return a duplicated bitmask.
  78. func (b Bitmask) Clone() Bitmask {
  79. bb := make(Bitmask, len(b))
  80. copy(bb, b)
  81. return bb
  82. }
  83. // NewBitmask returns a bitmask with length always rounded to a multiple of
  84. // sizeof(uint64). The input param n represents the bit count of this bitmask.
  85. func NewBitmask(n int) Bitmask {
  86. return make(Bitmask, (n+63)/64)
  87. }