buffer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. n := 0
  34. for err == nil && b.length < need {
  35. n, err = b.rd.Read(b.buf[b.length:])
  36. b.length += n
  37. }
  38. return
  39. }
  40. // read len(p) bytes
  41. func (b *buffer) read(p []byte) (err error) {
  42. need := len(p)
  43. if b.length < need {
  44. if b.length > 0 {
  45. copy(p[0:b.length], b.buf[b.idx:])
  46. need -= b.length
  47. p = p[b.length:]
  48. b.idx = 0
  49. b.length = 0
  50. }
  51. if need >= len(b.buf) {
  52. var n int
  53. has := 0
  54. for err == nil && need > has {
  55. n, err = b.rd.Read(p[has:])
  56. has += n
  57. }
  58. return
  59. }
  60. err = b.fill(need) // err deferred
  61. }
  62. copy(p, b.buf[b.idx:])
  63. b.idx += need
  64. b.length -= need
  65. return
  66. }