buffer.go 1.4 KB

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