buf.go (1946B)
1 package pq 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "errors" 7 "fmt" 8 9 "github.com/lib/pq/internal/proto" 10 "github.com/lib/pq/oid" 11 ) 12 13 type readBuf []byte 14 15 func (b *readBuf) int32() (n int) { 16 n = int(int32(binary.BigEndian.Uint32(*b))) 17 *b = (*b)[4:] 18 return 19 } 20 21 func (b *readBuf) oid() (n oid.Oid) { 22 n = oid.Oid(binary.BigEndian.Uint32(*b)) 23 *b = (*b)[4:] 24 return 25 } 26 27 // N.B: this is actually an unsigned 16-bit integer, unlike int32 28 func (b *readBuf) int16() (n int) { 29 n = int(binary.BigEndian.Uint16(*b)) 30 *b = (*b)[2:] 31 return 32 } 33 34 func (b *readBuf) string() string { 35 i := bytes.IndexByte(*b, 0) 36 if i < 0 { 37 panic(errors.New("pq: invalid message format; expected string terminator")) 38 } 39 s := (*b)[:i] 40 *b = (*b)[i+1:] 41 return string(s) 42 } 43 44 func (b *readBuf) next(n int) (v []byte) { 45 v = (*b)[:n] 46 *b = (*b)[n:] 47 return 48 } 49 50 func (b *readBuf) byte() byte { 51 return b.next(1)[0] 52 } 53 54 type writeBuf struct { 55 buf []byte 56 pos int 57 } 58 59 func (b *writeBuf) int32(n int) { 60 x := make([]byte, 4) 61 binary.BigEndian.PutUint32(x, uint32(n)) 62 b.buf = append(b.buf, x...) 63 } 64 65 func (b *writeBuf) int16(n int) { 66 x := make([]byte, 2) 67 binary.BigEndian.PutUint16(x, uint16(n)) 68 b.buf = append(b.buf, x...) 69 } 70 71 func (b *writeBuf) string(s string) { 72 b.buf = append(append(b.buf, s...), '\000') 73 } 74 75 func (b *writeBuf) byte(c proto.RequestCode) { 76 b.buf = append(b.buf, byte(c)) 77 } 78 79 func (b *writeBuf) bytes(v []byte) { 80 b.buf = append(b.buf, v...) 81 } 82 83 func (b *writeBuf) wrap() []byte { 84 p := b.buf[b.pos:] 85 if len(p) > proto.MaxUint32 { 86 panic(fmt.Errorf("pq: message too large (%d > math.MaxUint32)", len(p))) 87 } 88 binary.BigEndian.PutUint32(p, uint32(len(p))) 89 return b.buf 90 } 91 92 func (b *writeBuf) next(c proto.RequestCode) { 93 p := b.buf[b.pos:] 94 if len(p) > proto.MaxUint32 { 95 panic(fmt.Errorf("pq: message too large (%d > math.MaxUint32)", len(p))) 96 } 97 binary.BigEndian.PutUint32(p, uint32(len(p))) 98 b.pos = len(b.buf) + 1 99 b.buf = append(b.buf, byte(c), 0, 0, 0, 0) 100 }