-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbitreader.go
81 lines (71 loc) · 1.66 KB
/
bitreader.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
73
74
75
76
77
78
79
80
81
package d2s
import "io"
// bitReader wraps an io.Reader and provides the ability to read values,
// bit-by-bit, from it. Its Read* methods don't return the usual error
// because the error handling was verbose. Instead, any error is kept and can
// be checked afterwards.
type bitReader struct {
r io.ByteReader
n uint64
bits uint
err error
}
// ReadBits64 reads the given number of bits and returns them in the
// least-significant part of a uint64. In the event of an error, it returns 0
// and the error can be obtained by calling Err().
func (br *bitReader) ReadBits64(bits uint, reverse bool) (n uint64) {
for bits > br.bits {
b, err := br.r.ReadByte()
if reverse {
b = reverseByte(b)
}
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
if err != nil {
br.err = err
return 0
}
br.n <<= 8
br.n |= uint64(b)
br.bits += 8
}
// br.n looks like this (assuming that br.bits = 14 and bits = 6):
// Bit: 111111
// 5432109876543210
//
// (6 bits, the desired output)
// |-----|
// V V
// 0101101101001110
// ^ ^
// |------------|
// br.bits (num valid bits)
//
// This the next line right shifts the desired bits into the
// least-significant places and masks off anything above.
n = (br.n >> (br.bits - bits)) & ((1 << bits) - 1)
br.bits -= bits
return
}
func reverseByte(b byte) byte {
var d byte
for i := 0; i < 8; i++ {
d <<= 1
d |= b & 1
b >>= 1
}
return d
}
func reverseBits(b uint64, n uint) uint64 {
var d uint64
for i := 0; i < int(n); i++ {
d <<= 1
d |= b & 1
b >>= 1
}
return d
}
func (br *bitReader) Err() error {
return br.err
}