buffer.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 (
  11. "io"
  12. )
  13. const (
  14. defaultBufSize = 4096
  15. )
  16. type buffer struct {
  17. buf []byte
  18. rd io.Reader
  19. idx int
  20. length int
  21. }
  22. func newBuffer(rd io.Reader) *buffer {
  23. return &buffer{
  24. buf: make([]byte, defaultBufSize),
  25. rd: rd,
  26. }
  27. }
  28. // fill reads at least _need_ bytes in the buffer
  29. // existing data in the buffer gets lost
  30. func (b *buffer) fill(need int) (err error) {
  31. b.idx = 0
  32. b.length = 0
  33. var n int
  34. for b.length < need {
  35. n, err = b.rd.Read(b.buf[b.length:])
  36. b.length += n
  37. if err == nil {
  38. continue
  39. }
  40. return // err
  41. }
  42. return
  43. }
  44. // returns next N bytes from buffer.
  45. // The returned slice is only guaranteed to be valid until the next read
  46. func (b *buffer) readNext(need int) (p []byte, err error) {
  47. // return slice from buffer if possible
  48. if b.length >= need {
  49. p = b.buf[b.idx : b.idx+need]
  50. b.idx += need
  51. b.length -= need
  52. return
  53. } else {
  54. p = make([]byte, need)
  55. has := 0
  56. // copy data that is already in the buffer
  57. if b.length > 0 {
  58. copy(p[0:b.length], b.buf[b.idx:])
  59. has = b.length
  60. need -= has
  61. b.idx = 0
  62. b.length = 0
  63. }
  64. // does the data fit into the buffer?
  65. if need < len(b.buf) {
  66. err = b.fill(need) // err deferred
  67. copy(p[has:has+need], b.buf[b.idx:])
  68. b.idx += need
  69. b.length -= need
  70. return
  71. } else {
  72. var n int
  73. for err == nil && need > 0 {
  74. n, err = b.rd.Read(p[has:])
  75. has += n
  76. need -= n
  77. }
  78. }
  79. }
  80. return
  81. }