bitlist.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package barcode
  2. type BitList struct {
  3. count int
  4. data []int32
  5. }
  6. func NewBitList(capacity int) *BitList {
  7. bl := new(BitList)
  8. bl.count = capacity
  9. x := 0
  10. if capacity%32 != 0 {
  11. x = 1
  12. }
  13. bl.data = make([]int32, capacity/32+x)
  14. return bl
  15. }
  16. func (bl *BitList) Len() int {
  17. return bl.count
  18. }
  19. func (bl *BitList) Cap() int {
  20. return len(bl.data) * 32
  21. }
  22. func (bl *BitList) grow() {
  23. growBy := len(bl.data)
  24. if growBy < 128 {
  25. growBy = 128
  26. } else if growBy >= 1024 {
  27. growBy = 1024
  28. }
  29. nd := make([]int32, len(bl.data)+growBy)
  30. copy(nd, bl.data)
  31. bl.data = nd
  32. }
  33. func (bl *BitList) AddBit(bit bool) {
  34. itmIndex := bl.count / 32
  35. for itmIndex >= len(bl.data) {
  36. bl.grow()
  37. }
  38. bl.SetBit(bl.count, bit)
  39. bl.count++
  40. }
  41. func (bl *BitList) SetBit(index int, value bool) {
  42. itmIndex := index / 32
  43. itmBitShift := 31 - (index % 32)
  44. if value {
  45. bl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift)
  46. } else {
  47. bl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift))
  48. }
  49. }
  50. func (bl *BitList) GetBit(index int) bool {
  51. itmIndex := index / 32
  52. itmBitShift := 31 - (index % 32)
  53. return ((bl.data[itmIndex] >> uint(itmBitShift)) & 1) == 1
  54. }
  55. func (bl *BitList) AddByte(b byte) {
  56. for i := 7; i >= 0; i-- {
  57. bl.AddBit(((b >> uint(i)) & 1) == 1)
  58. }
  59. }
  60. func (bl *BitList) AddBits(b int, count byte) {
  61. for i := int(count - 1); i >= 0; i-- {
  62. bl.AddBit(((b >> uint(i)) & 1) == 1)
  63. }
  64. }
  65. func (bl *BitList) GetBytes() []byte {
  66. len := bl.count >> 3
  67. if (bl.count % 8) != 0 {
  68. len += 1
  69. }
  70. result := make([]byte, len)
  71. for i := 0; i < len; i++ {
  72. shift := (3 - (i % 4)) * 8
  73. result[i] = (byte)((bl.data[i/4] >> uint(shift)) & 0xFF)
  74. }
  75. return result
  76. }
  77. func (bl *BitList) ItterateBytes() <-chan byte {
  78. res := make(chan byte)
  79. go func() {
  80. c := bl.count
  81. shift := 24
  82. i := 0
  83. for c > 0 {
  84. res <- byte((bl.data[i] >> uint(shift)) & 0xFF)
  85. shift -= 8
  86. if shift < 0 {
  87. shift = 24
  88. i += 1
  89. }
  90. c -= 8
  91. }
  92. close(res)
  93. }()
  94. return res
  95. }