forked from go-sql-driver/mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
88 lines (73 loc) · 1.82 KB
/
buffer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2013 Julien Schmidt. All rights reserved.
// http://www.julienschmidt.com
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package mysql
import "io"
const defaultBufSize = 4096
type buffer struct {
buf []byte
rd io.Reader
idx int
length int
}
func newBuffer(rd io.Reader) *buffer {
return &buffer{
buf: make([]byte, defaultBufSize),
rd: rd,
}
}
// fill reads into the buffer until at least _need_ bytes are in it
func (b *buffer) fill(need int) (err error) {
// move existing data to the beginning
if b.length > 0 && b.idx > 0 {
copy(b.buf[0:b.length], b.buf[b.idx:])
}
// grow buffer if necessary
if need > len(b.buf) {
b.grow(need)
}
b.idx = 0
var n int
for b.length < need {
n, err = b.rd.Read(b.buf[b.length:])
b.length += n
if err == nil {
continue
}
return // err
}
return
}
// grow the buffer to at least the given size
// credit for this code snippet goes to Maxim Khitrov
// https://groups.google.com/forum/#!topic/golang-nuts/ETbw1ECDgRs
func (b *buffer) grow(size int) {
// If append would be too expensive, alloc a new slice
if size > 2*cap(b.buf) {
newBuf := make([]byte, size)
copy(newBuf, b.buf)
b.buf = newBuf
return
}
for cap(b.buf) < size {
b.buf = append(b.buf[:cap(b.buf)], 0)
}
b.buf = b.buf[:cap(b.buf)]
}
// returns next N bytes from buffer.
// The returned slice is only guaranteed to be valid until the next read
func (b *buffer) readNext(need int) (p []byte, err error) {
if b.length < need {
// refill
err = b.fill(need) // err deferred
}
p = b.buf[b.idx : b.idx+need]
b.idx += need
b.length -= need
return
}