buffer.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 Julien Schmidt. All rights reserved.
  4. // http://www.julienschmidt.com
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public
  7. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  8. // You can obtain one at http://mozilla.org/MPL/2.0/.
  9. package mysql
  10. import "io"
  11. const defaultBufSize = 4096
  12. // A read buffer similar to bufio.Reader but zero-copy-ish
  13. // Also highly optimized for this particular use case.
  14. type buffer struct {
  15. buf []byte
  16. rd io.Reader
  17. idx int
  18. length int
  19. }
  20. func newBuffer(rd io.Reader) *buffer {
  21. var b [defaultBufSize]byte
  22. return &buffer{
  23. buf: b[:],
  24. rd: rd,
  25. }
  26. }
  27. // fill reads into the buffer until at least _need_ bytes are in it
  28. func (b *buffer) fill(need int) (err error) {
  29. // move existing data to the beginning
  30. if b.length > 0 && b.idx > 0 {
  31. copy(b.buf[0:b.length], b.buf[b.idx:])
  32. }
  33. // grow buffer if necessary
  34. if need > len(b.buf) {
  35. newBuf := make([]byte, need)
  36. copy(newBuf, b.buf)
  37. b.buf = newBuf
  38. }
  39. b.idx = 0
  40. var n int
  41. for {
  42. n, err = b.rd.Read(b.buf[b.length:])
  43. b.length += n
  44. if b.length < need && err == nil {
  45. continue
  46. }
  47. return // err
  48. }
  49. return
  50. }
  51. // returns next N bytes from buffer.
  52. // The returned slice is only guaranteed to be valid until the next read
  53. func (b *buffer) readNext(need int) (p []byte, err error) {
  54. if b.length < need {
  55. // refill
  56. err = b.fill(need) // err deferred
  57. }
  58. p = b.buf[b.idx : b.idx+need]
  59. b.idx += need
  60. b.length -= need
  61. return
  62. }