-
Notifications
You must be signed in to change notification settings - Fork 1
/
BitBuffer.go
67 lines (57 loc) · 1.28 KB
/
BitBuffer.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
package ccittfaxdecode
type bitBuffer struct {
Buffer uint32
EmptyBits uint8
source []byte
sourcePos uint
}
func (b *bitBuffer) FlushBits(count uint8) {
b.Buffer = b.Buffer << count
b.EmptyBits += count
b.tryfillBuffer()
}
func (b *bitBuffer) Peak8() (uint8, uint8) {
return uint8(b.Buffer >> 24), 32 - b.EmptyBits
}
func (b *bitBuffer) Peak16() (uint16, uint8) {
return uint16(b.Buffer >> 16), 32 - b.EmptyBits
}
func (b *bitBuffer) Peak32() (uint32, uint8) {
return b.Buffer, 32 - b.EmptyBits
}
func (b *bitBuffer) HasData() bool {
if b.EmptyBits == 32 && int(b.sourcePos) >= len(b.source) {
return false
}
return true
}
func (b *bitBuffer) Clear() {
b.Buffer = 0
b.EmptyBits = 32
b.sourcePos = 0
}
func (b *bitBuffer) tryfillBuffer() {
for b.EmptyBits > 7 {
if b.sourcePos >= uint(len(b.source)) {
break
}
b.AddByte(b.source[b.sourcePos])
b.sourcePos++
}
}
func newBitBuffer(source []byte) *bitBuffer {
buffer := &bitBuffer{
EmptyBits: 32,
Buffer: 0,
source: source,
sourcePos: 0,
}
buffer.tryfillBuffer()
return buffer
}
func (b *bitBuffer) AddByte(source byte) {
padRight := b.EmptyBits - 8
zeroed := b.Buffer >> (8 + padRight) << (8 + padRight) // switch to hex AND?
b.Buffer = zeroed | (uint32(source) << padRight)
b.EmptyBits -= 8
}