You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.6 KiB

  1. package pq
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "github.com/lib/pq/oid"
  6. )
  7. type readBuf []byte
  8. func (b *readBuf) int32() (n int) {
  9. n = int(int32(binary.BigEndian.Uint32(*b)))
  10. *b = (*b)[4:]
  11. return
  12. }
  13. func (b *readBuf) oid() (n oid.Oid) {
  14. n = oid.Oid(binary.BigEndian.Uint32(*b))
  15. *b = (*b)[4:]
  16. return
  17. }
  18. // N.B: this is actually an unsigned 16-bit integer, unlike int32
  19. func (b *readBuf) int16() (n int) {
  20. n = int(binary.BigEndian.Uint16(*b))
  21. *b = (*b)[2:]
  22. return
  23. }
  24. func (b *readBuf) string() string {
  25. i := bytes.IndexByte(*b, 0)
  26. if i < 0 {
  27. errorf("invalid message format; expected string terminator")
  28. }
  29. s := (*b)[:i]
  30. *b = (*b)[i+1:]
  31. return string(s)
  32. }
  33. func (b *readBuf) next(n int) (v []byte) {
  34. v = (*b)[:n]
  35. *b = (*b)[n:]
  36. return
  37. }
  38. func (b *readBuf) byte() byte {
  39. return b.next(1)[0]
  40. }
  41. type writeBuf struct {
  42. buf []byte
  43. pos int
  44. }
  45. func (b *writeBuf) int32(n int) {
  46. x := make([]byte, 4)
  47. binary.BigEndian.PutUint32(x, uint32(n))
  48. b.buf = append(b.buf, x...)
  49. }
  50. func (b *writeBuf) int16(n int) {
  51. x := make([]byte, 2)
  52. binary.BigEndian.PutUint16(x, uint16(n))
  53. b.buf = append(b.buf, x...)
  54. }
  55. func (b *writeBuf) string(s string) {
  56. b.buf = append(b.buf, (s + "\000")...)
  57. }
  58. func (b *writeBuf) byte(c byte) {
  59. b.buf = append(b.buf, c)
  60. }
  61. func (b *writeBuf) bytes(v []byte) {
  62. b.buf = append(b.buf, v...)
  63. }
  64. func (b *writeBuf) wrap() []byte {
  65. p := b.buf[b.pos:]
  66. binary.BigEndian.PutUint32(p, uint32(len(p)))
  67. return b.buf
  68. }
  69. func (b *writeBuf) next(c byte) {
  70. p := b.buf[b.pos:]
  71. binary.BigEndian.PutUint32(p, uint32(len(p)))
  72. b.pos = len(b.buf) + 1
  73. b.buf = append(b.buf, c, 0, 0, 0, 0)
  74. }