blob: 5b03b47faf2d420ce8fa057778634e9505ad318c [file] [log] [blame]
Julien Schmidtccad9562013-03-01 19:31:431// 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
10package mysql
11
12import (
13 "io"
14)
15
16const (
17 defaultBufSize = 4096
18)
19
20type buffer struct {
21 buf []byte
22 rd io.Reader
23 idx int
24 length int
25}
26
27func 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
36func (b *buffer) fill(need int) (err error) {
37 b.idx = 0
38 b.length = 0
39
40 n := 0
Julien Schmidt74a64522013-03-03 17:41:1341 for b.length < need {
Julien Schmidtccad9562013-03-01 19:31:4342 n, err = b.rd.Read(b.buf[b.length:])
43 b.length += n
Julien Schmidt74a64522013-03-03 17:41:1344
45 if err == nil {
46 continue
47 }
48 return // err
Julien Schmidtccad9562013-03-01 19:31:4349 }
50
51 return
52}
53
54// read len(p) bytes
55func (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}