-
Notifications
You must be signed in to change notification settings - Fork 37
/
packer.go
114 lines (97 loc) · 2.53 KB
/
packer.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
104
105
106
107
108
109
110
111
112
113
114
package binpacker
import (
"encoding/binary"
"io"
"math"
)
// Packer is a binary packer helps you pack data into an io.Writer.
type Packer struct {
writer io.Writer
endian binary.ByteOrder
err error
}
// NewPacker returns a *Packer hold an io.Writer. User must provide the byte order explicitly.
func NewPacker(endian binary.ByteOrder, writer io.Writer) *Packer {
return &Packer{
writer: writer,
endian: endian,
}
}
// Error returns an error if any errors exists
func (p *Packer) Error() error {
return p.err
}
// PushByte write a single byte into writer.
func (p *Packer) PushByte(b byte) *Packer {
return p.errFilter(func() {
_, p.err = p.writer.Write([]byte{b})
})
}
// PushBytes write a bytes array into writer.
func (p *Packer) PushBytes(bytes []byte) *Packer {
return p.errFilter(func() {
_, p.err = p.writer.Write(bytes)
})
}
// PushUint8 write a uint8 into writer.
func (p *Packer) PushUint8(i uint8) *Packer {
return p.errFilter(func() {
_, p.err = p.writer.Write([]byte{byte(i)})
})
}
// PushUint16 write a uint16 into writer.
func (p *Packer) PushUint16(i uint16) *Packer {
return p.errFilter(func() {
buffer := make([]byte, 2)
p.endian.PutUint16(buffer, i)
_, p.err = p.writer.Write(buffer)
})
}
// PushUint16 write a int16 into writer.
func (p *Packer) PushInt16(i int16) *Packer {
return p.PushUint16(uint16(i))
}
// PushUint32 write a uint32 into writer.
func (p *Packer) PushUint32(i uint32) *Packer {
return p.errFilter(func() {
buffer := make([]byte, 4)
p.endian.PutUint32(buffer, i)
_, p.err = p.writer.Write(buffer)
})
}
// PushInt32 write a int32 into writer.
func (p *Packer) PushInt32(i int32) *Packer {
return p.PushUint32(uint32(i))
}
// PushUint64 write a uint64 into writer.
func (p *Packer) PushUint64(i uint64) *Packer {
return p.errFilter(func() {
buffer := make([]byte, 8)
p.endian.PutUint64(buffer, i)
_, p.err = p.writer.Write(buffer)
})
}
// PushInt64 write a int64 into writer.
func (p *Packer) PushInt64(i int64) *Packer {
return p.PushUint64(uint64(i))
}
// PushFloat32 write a float32 into writer.
func (p *Packer) PushFloat32(i float32) *Packer {
return p.PushUint32(math.Float32bits(i))
}
// PushFloat64 write a float64 into writer.
func (p *Packer) PushFloat64(i float64) *Packer {
return p.PushUint64(math.Float64bits(i))
}
// PushString write a string into writer.
func (p *Packer) PushString(s string) *Packer {
return p.errFilter(func() {
_, p.err = p.writer.Write([]byte(s))
})
}
func (p *Packer) errFilter(f func()) *Packer {
if p.err == nil {
f()
}
return p
}