-
Notifications
You must be signed in to change notification settings - Fork 84
/
bytewriter.go
79 lines (69 loc) · 1.5 KB
/
bytewriter.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
package bits
import (
"encoding/binary"
"io"
)
// ByteWriter - writer that wraps an io.Writer and accumulates error.
// Only the first error is saved, but any later calls will not panic.
type ByteWriter struct {
w io.Writer
err error
}
// NewByteWriter creates accumulated error writer around io.Writer.
func NewByteWriter(w io.Writer) *ByteWriter {
return &ByteWriter{
w: w,
}
}
// AccError - return accumulated error
func (a *ByteWriter) AccError() error {
return a.err
}
// WriteUint8 - write a byte
func (a *ByteWriter) WriteUint8(b byte) {
if a.err != nil {
return
}
a.err = binary.Write(a.w, binary.BigEndian, b)
}
// WriteUint16 - write uint16
func (a *ByteWriter) WriteUint16(u uint16) {
if a.err != nil {
return
}
a.err = binary.Write(a.w, binary.BigEndian, u)
}
// WriteUint32 - write uint32
func (a *ByteWriter) WriteUint32(u uint32) {
if a.err != nil {
return
}
a.err = binary.Write(a.w, binary.BigEndian, u)
}
// WriteUint48 - write uint48
func (a *ByteWriter) WriteUint48(u uint64) {
if a.err != nil {
return
}
msb := uint16(u >> 32)
a.err = binary.Write(a.w, binary.BigEndian, msb)
if a.err != nil {
return
}
lsb := uint32(u & 0xffffffff)
a.err = binary.Write(a.w, binary.BigEndian, lsb)
}
// WriteUint64 - write uint64
func (a *ByteWriter) WriteUint64(u uint64) {
if a.err != nil {
return
}
a.err = binary.Write(a.w, binary.BigEndian, u)
}
// WriteSlice - write a slice
func (a *ByteWriter) WriteSlice(s []byte) {
if a.err != nil {
return
}
_, a.err = a.w.Write(s)
}