-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhybrid_writer.go
72 lines (59 loc) · 1.33 KB
/
hybrid_writer.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"encoding/binary"
)
type hybridWriter struct {
buf []byte
offset int
bitWidthNBytes int
// TODO: we aren't doing any bitpacking yet
currRLEVal int32
currRLELength int
scratch [4]byte
}
func newHybridWriter(nValues, bitWidth int) *hybridWriter {
bitWidthNBytes := (bitWidth + 7) / 8
return &hybridWriter{
buf: make([]byte, nValues*(binary.MaxVarintLen64+bitWidthNBytes)),
bitWidthNBytes: bitWidthNBytes,
}
}
func (hw *hybridWriter) Write(v int32) {
if v == hw.currRLEVal {
hw.currRLELength += 1
return
}
hw.flush()
hw.currRLEVal = v
}
func (hw *hybridWriter) Flush() []byte {
hw.flush()
return hw.buf[:hw.offset]
}
func (hw *hybridWriter) flush() {
n := binary.PutUvarint(hw.buf[hw.offset:], uint64(hw.currRLELength<<1))
hw.offset += n
buf := hw.buf[hw.offset:]
switch hw.bitWidthNBytes {
case 1:
buf[0] = byte(hw.currRLEVal)
case 2:
_ = buf[1]
buf[0] = byte(hw.currRLEVal)
buf[1] = byte(hw.currRLEVal >> 8)
case 3:
_ = buf[2]
buf[0] = byte(hw.currRLEVal)
buf[1] = byte(hw.currRLEVal >> 8)
buf[2] = byte(hw.currRLEVal >> 16)
case 4:
_ = buf[3]
buf[0] = byte(hw.currRLEVal)
buf[1] = byte(hw.currRLEVal >> 8)
buf[2] = byte(hw.currRLEVal >> 16)
buf[3] = byte(hw.currRLEVal >> 24)
default:
panic("Bad int size")
}
hw.offset += hw.bitWidthNBytes
}