-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpgpacket.go
94 lines (76 loc) · 1.82 KB
/
pgpacket.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
package main
// Buffer type (taken directly from https://github.com/lib/pq/blob/master/buf.go)
import (
"bytes"
"encoding/binary"
log "github.com/Sirupsen/logrus"
"github.com/lib/pq/oid"
)
type postgresRequest []byte
func (b *postgresRequest) int32() (n int) {
n = int(int32(binary.BigEndian.Uint32(*b)))
*b = (*b)[4:]
return
}
func (b *postgresRequest) oid() (n oid.Oid) {
n = oid.Oid(binary.BigEndian.Uint32(*b))
*b = (*b)[4:]
return
}
// N.B: this is actually an unsigned 16-bit integer, unlike int32
func (b *postgresRequest) int16() (n int) {
n = int(binary.BigEndian.Uint16(*b))
*b = (*b)[2:]
return
}
func (b *postgresRequest) string() string {
i := bytes.IndexByte(*b, 0)
if i < 0 {
log.Error("invalid message format; expected string terminator")
}
s := (*b)[:i]
*b = (*b)[i+1:]
return string(s)
}
func (b *postgresRequest) next(n int) (v []byte) {
v = (*b)[:n]
*b = (*b)[n:]
return
}
func (b *postgresRequest) byte() byte {
return b.next(1)[0]
}
type postgresResponse struct {
buf []byte
pos int
}
func (b *postgresResponse) int32(n int) {
x := make([]byte, 4)
binary.BigEndian.PutUint32(x, uint32(n))
b.buf = append(b.buf, x...)
}
func (b *postgresResponse) int16(n int) {
x := make([]byte, 2)
binary.BigEndian.PutUint16(x, uint16(n))
b.buf = append(b.buf, x...)
}
func (b *postgresResponse) string(s string) {
b.buf = append(b.buf, (s + "\000")...)
}
func (b *postgresResponse) byte(c byte) {
b.buf = append(b.buf, c)
}
func (b *postgresResponse) bytes(v []byte) {
b.buf = append(b.buf, v...)
}
func (b *postgresResponse) wrap() []byte {
p := b.buf[b.pos:]
binary.BigEndian.PutUint32(p, uint32(len(p)))
return b.buf
}
func (b *postgresResponse) next(c byte) {
p := b.buf[b.pos:]
binary.BigEndian.PutUint32(p, uint32(len(p)))
b.pos = len(b.buf) + 1
b.buf = append(b.buf, c, 0, 0, 0, 0)
}