Julien Schmidt | ccad956 | 2013-03-01 19:31:43 | [diff] [blame] | 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 | |
| 10 | package mysql |
| 11 | |
| 12 | import ( |
| 13 | "io" |
| 14 | ) |
| 15 | |
| 16 | const ( |
| 17 | defaultBufSize = 4096 |
| 18 | ) |
| 19 | |
| 20 | type buffer struct { |
| 21 | buf []byte |
| 22 | rd io.Reader |
| 23 | idx int |
| 24 | length int |
| 25 | } |
| 26 | |
| 27 | func newBuffer(rd io.Reader) *buffer { |
| 28 | return &buffer{ |
| 29 | buf: make([]byte, defaultBufSize), |
| 30 | rd: rd, |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // fill reads at least _need_ bytes in the buffer |
| 35 | // existing data in the buffer gets lost |
| 36 | func (b *buffer) fill(need int) (err error) { |
| 37 | b.idx = 0 |
| 38 | b.length = 0 |
| 39 | |
| 40 | n := 0 |
Julien Schmidt | 74a6452 | 2013-03-03 17:41:13 | [diff] [blame^] | 41 | for b.length < need { |
Julien Schmidt | ccad956 | 2013-03-01 19:31:43 | [diff] [blame] | 42 | n, err = b.rd.Read(b.buf[b.length:]) |
| 43 | b.length += n |
Julien Schmidt | 74a6452 | 2013-03-03 17:41:13 | [diff] [blame^] | 44 | |
| 45 | if err == nil { |
| 46 | continue |
| 47 | } |
| 48 | return // err |
Julien Schmidt | ccad956 | 2013-03-01 19:31:43 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | return |
| 52 | } |
| 53 | |
| 54 | // read len(p) bytes |
| 55 | func (b *buffer) read(p []byte) (err error) { |
| 56 | need := len(p) |
| 57 | |
| 58 | if b.length < need { |
| 59 | if b.length > 0 { |
| 60 | copy(p[0:b.length], b.buf[b.idx:]) |
| 61 | need -= b.length |
| 62 | p = p[b.length:] |
| 63 | |
| 64 | b.idx = 0 |
| 65 | b.length = 0 |
| 66 | } |
| 67 | |
| 68 | if need >= len(b.buf) { |
| 69 | var n int |
| 70 | has := 0 |
| 71 | for err == nil && need > has { |
| 72 | n, err = b.rd.Read(p[has:]) |
| 73 | has += n |
| 74 | } |
| 75 | return |
| 76 | } |
| 77 | |
| 78 | err = b.fill(need) // err deferred |
| 79 | } |
| 80 | |
| 81 | copy(p, b.buf[b.idx:]) |
| 82 | b.idx += need |
| 83 | b.length -= need |
| 84 | return |
| 85 | } |