forked from HugoSmits86/nativewebp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitwriter.go
executable file
·56 lines (46 loc) · 1.15 KB
/
bitwriter.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
package nativewebp
import (
//------------------------------
//general
//------------------------------
"bytes"
)
type bitWriter struct {
Buffer *bytes.Buffer
BitBuffer uint64
BitBufferSize int
}
func (w *bitWriter) writeBits(value uint64, n int) {
if n < 0 || n > 64 {
panic("Invalid bit count: must be between 1 and 64")
}
if value >= (1 << n) {
panic("too many bits for the given value")
}
w.BitBuffer |= (value << w.BitBufferSize)
w.BitBufferSize += n
w.writeThrough()
}
func (w *bitWriter) writeCode(code huffmanCode) {
if code.Depth <= 0 {
return
}
value := uint64(code.Bits)
reversed := uint64(0)
for i := 0; i < code.Depth; i++ {
reversed = (reversed << 1) | (value & 1)
value >>= 1
}
w.writeBits(reversed, code.Depth)
}
func (w *bitWriter) AlignByte() {
w.BitBufferSize = (w.BitBufferSize + 7) &^ 7
w.writeThrough()
}
func (w *bitWriter) writeThrough() {
for w.BitBufferSize >= 8 {
w.Buffer.WriteByte(byte(w.BitBuffer & 0xFF))
w.BitBuffer >>= 8
w.BitBufferSize -= 8
}
}