buf.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. func (b *readBuf) int16() (n int) {
  19. n = int(binary.BigEndian.Uint16(*b))
  20. *b = (*b)[2:]
  21. return
  22. }
  23. func (b *readBuf) string() string {
  24. i := bytes.IndexByte(*b, 0)
  25. if i < 0 {
  26. errorf("invalid message format; expected string terminator")
  27. }
  28. s := (*b)[:i]
  29. *b = (*b)[i+1:]
  30. return string(s)
  31. }
  32. func (b *readBuf) next(n int) (v []byte) {
  33. v = (*b)[:n]
  34. *b = (*b)[n:]
  35. return
  36. }
  37. func (b *readBuf) byte() byte {
  38. return b.next(1)[0]
  39. }
  40. type writeBuf []byte
  41. func (b *writeBuf) int32(n int) {
  42. x := make([]byte, 4)
  43. binary.BigEndian.PutUint32(x, uint32(n))
  44. *b = append(*b, x...)
  45. }
  46. func (b *writeBuf) int16(n int) {
  47. x := make([]byte, 2)
  48. binary.BigEndian.PutUint16(x, uint16(n))
  49. *b = append(*b, x...)
  50. }
  51. func (b *writeBuf) string(s string) {
  52. *b = append(*b, (s + "\000")...)
  53. }
  54. func (b *writeBuf) byte(c byte) {
  55. *b = append(*b, c)
  56. }
  57. func (b *writeBuf) bytes(v []byte) {
  58. *b = append(*b, v...)
  59. }