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_writer.go
88 lines (73 loc) · 1.72 KB
/
bit_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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gorilla
import (
"fmt"
"io"
)
type bitWriter struct {
w io.Writer
buffer byte
count uint8 // How many right-most bits are available for writing in the current byte (the last byte of the buffer).
}
// newBitWriter returns a writer that buffers bits and write the resulting bytes to 'w'
func newBitWriter(w io.Writer) *bitWriter {
return &bitWriter{
w: w, count: 8,
}
}
// writeBit writes a single bit.
func (b *bitWriter) writeBit(bit bit) error {
if bit {
b.buffer |= 1 << (b.count - 1)
}
b.count--
if b.count == 0 {
if _, err := b.w.Write([]byte{b.buffer}); err != nil {
return fmt.Errorf("failed to write a bit: %w", err)
}
b.buffer = 0
b.count = 8
}
return nil
}
// writeBits writes the nbits right-most bits of u64 to the buffer in left-to-right order.
func (b *bitWriter) writeBits(u64 uint64, nbits int) error {
u64 <<= (64 - uint(nbits))
for nbits >= 8 {
byt := byte(u64 >> 56)
err := b.writeByte(byt)
if err != nil {
return err
}
u64 <<= 8
nbits -= 8
}
for nbits > 0 {
err := b.writeBit((u64 >> 63) == 1)
if err != nil {
return err
}
u64 <<= 1
nbits--
}
return nil
}
// writeByte writes a single byte to the stream, regardless of alignment
func (b *bitWriter) writeByte(byt byte) error {
// Complete the last byte with the leftmost b.buffer bits from byt.
b.buffer |= byt >> (8 - b.count)
if _, err := b.w.Write([]byte{b.buffer}); err != nil {
return fmt.Errorf("failed to write a byte: %w", err)
}
b.buffer = byt << b.count
return nil
}
// flush empties the currently in-process byte by filling it with 'bit'.
func (b *bitWriter) flush(bit bit) error {
for b.count != 8 {
err := b.writeBit(bit)
if err != nil {
return err
}
}
return nil
}