This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
bit_reader.go
103 lines (89 loc) · 2.06 KB
/
bit_reader.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package gorilla
import (
"errors"
"fmt"
"io"
)
// A reader reads bits from an io.reader
type bitReader struct {
r io.Reader
buffer [1]byte
count uint8 // The number of right-most bits valid to read (from left) in the current 8 byte buffer.
}
// newReader returns a reader that returns a single bit at a time from 'r'
func newBitReader(r io.Reader) *bitReader {
return &bitReader{r: r}
}
// readBit returns the next bit from the stream, reading a new byte
// from the underlying reader if required.
func (b *bitReader) readBit() (bit, error) {
if b.count == 0 {
n, err := b.r.Read(b.buffer[:])
if err != nil {
return zero, fmt.Errorf("failed to read a byte: %w", err)
}
if n != 1 {
return zero, errors.New("read more than a byte")
}
b.count = 8
}
b.count--
// bitwise AND
// (e.g.)
// 11111111 & 10000000 = 10000000
// 11000011 & 10000000 = 10000000
d := (b.buffer[0] & 0x80)
// Left shift to read next bit
b.buffer[0] <<= 1
return d != 0, nil
}
// readBits constructs a uint64 with the nbits right-most bits
// read from the stream, and any other bits 0.
func (b *bitReader) readByte() (byte, error) {
if b.count == 0 {
n, err := b.r.Read(b.buffer[:])
if err != nil {
return b.buffer[0], fmt.Errorf("failed to read a byte: %w", err)
}
if n != 1 {
return b.buffer[0], errors.New("read more than a byte")
}
return b.buffer[0], nil
}
byt := b.buffer[0]
n, err := b.r.Read(b.buffer[:])
if err != nil {
return 0, fmt.Errorf("failed to read a byte: %w", err)
}
if n != 1 {
return b.buffer[0], errors.New("read more than a byte")
}
byt |= b.buffer[0] >> b.count
b.buffer[0] <<= (8 - b.count)
return byt, nil
}
// readBits reads nbits from the stream
func (b *bitReader) readBits(nbits int) (uint64, error) {
var u uint64
for 8 <= nbits {
byt, err := b.readByte()
if err != nil {
return 0, err
}
u = (u << 8) | uint64(byt)
nbits -= 8
}
var err error
for nbits > 0 && err != io.EOF {
byt, err := b.readBit()
if err != nil {
return 0, err
}
u <<= 1
if byt {
u |= 1
}
nbits--
}
return u, nil
}