forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
91 lines (73 loc) · 1.6 KB
/
buffer.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
package pg
import (
"encoding/binary"
"io"
)
type buffer struct {
B []byte
b8 []byte
start int // Message start position.
}
func newBuffer() *buffer {
return &buffer{
B: make([]byte, 0, 8192),
b8: make([]byte, 8),
}
}
func (buf *buffer) StartMessage(c msgType) {
if len(buf.B) > 0 {
buf.closeMessage()
}
if c == 0 {
buf.start = len(buf.B)
buf.B = append(buf.B, 0, 0, 0, 0)
} else {
buf.start = len(buf.B) + 1
buf.B = append(buf.B, byte(c), 0, 0, 0, 0)
}
}
func (buf *buffer) closeMessage() {
binary.BigEndian.PutUint32(buf.B[buf.start:], uint32(len(buf.B)-buf.start))
}
func (buf *buffer) Grow(n int) {
buf.B = append(buf.B, buf.b8[:n]...)
}
func (buf *buffer) Write(b []byte) (int, error) {
buf.B = append(buf.B, b...)
return len(b), nil
}
func (buf *buffer) WriteInt16(num int16) {
buf.Grow(2)
binary.BigEndian.PutUint16(buf.B[len(buf.B)-2:], uint16(num))
}
func (buf *buffer) WriteInt32(num int32) {
buf.Grow(4)
binary.BigEndian.PutUint32(buf.B[len(buf.B)-4:], uint32(num))
}
func (buf *buffer) WriteString(s string) {
buf.B = append(buf.B, s...)
buf.B = append(buf.B, 0)
}
func (buf *buffer) WriteBytes(b []byte) {
buf.B = append(buf.B, b...)
buf.B = append(buf.B, 0)
}
func (buf *buffer) WriteByte(c byte) {
buf.B = append(buf.B, c)
}
func (buf *buffer) Flush() []byte {
if len(buf.B) > 0 {
buf.closeMessage()
}
b := buf.B[:]
buf.B = buf.B[:0]
return b
}
func (buf *buffer) Reset() {
buf.B = buf.B[:0]
}
func (buf *buffer) ReadFrom(r io.Reader) (int64, error) {
n, err := r.Read(buf.B[len(buf.B):cap(buf.B)])
buf.B = buf.B[:len(buf.B)+int(n)]
return int64(n), err
}