/
bitpacker.go
49 lines (42 loc) · 1.11 KB
/
bitpacker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package chipmunk
import (
"bytes"
"encoding/binary"
bitopts "github.com/cmchao/go-bitops"
)
type bitPacker struct {
array []uint64
currentIdx int
currentBit uint
}
func newBitPacker() *bitPacker {
vp := &bitPacker{array: make([]uint64, 1), currentBit: 63}
return vp
}
func (vp *bitPacker) Add(length uint, value uint64) {
lowbit := int64(vp.currentBit) - (int64(length) - 1)
if lowbit < 0 {
sr := uint64(length) - (uint64(vp.currentBit) + 1)
fieldVal := value >> sr
vp.array[vp.currentIdx], _ = bitopts.SetField64(vp.array[vp.currentIdx], vp.currentBit, 0, uint64(fieldVal))
vp.array = append(vp.array, uint64(value<<(64-sr)))
vp.currentBit = 63 - uint(sr)
vp.currentIdx++
} else {
vp.array[vp.currentIdx], _ = bitopts.SetField64(vp.array[vp.currentIdx], vp.currentBit, uint(lowbit), value)
if lowbit == 0 {
vp.array = append(vp.array, uint64(0))
vp.currentBit = 63
vp.currentIdx++
} else {
vp.currentBit = uint(lowbit) - 1
}
}
}
func (vp *bitPacker) Bytes() []byte {
var b bytes.Buffer
for _, val := range vp.array {
binary.Write(&b, binary.BigEndian, val)
}
return b.Bytes()
}