File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change @@ -13,6 +13,8 @@ import "io"
13
13
14
14
const defaultBufSize = 4096
15
15
16
+ // A read buffer similar to bufio.Reader but zero-copy-ish
17
+ // Also highly optimized for this particular use case.
16
18
type buffer struct {
17
19
buf []byte
18
20
rd io.Reader
@@ -42,35 +44,38 @@ func (b *buffer) fill(need int) (err error) {
42
44
b .idx = 0
43
45
44
46
var n int
45
- for b . length < need {
47
+ for {
46
48
n , err = b .rd .Read (b .buf [b .length :])
47
49
b .length += n
48
50
49
- if err == nil {
51
+ if b . length < need && err == nil {
50
52
continue
51
53
}
52
54
return // err
53
55
}
54
-
55
- return
56
56
}
57
57
58
58
// grow the buffer to at least the given size
59
59
// credit for this code snippet goes to Maxim Khitrov
60
60
// https://groups.google.com/forum/#!topic/golang-nuts/ETbw1ECDgRs
61
61
func (b * buffer ) grow (size int ) {
62
62
// If append would be too expensive, alloc a new slice
63
- if size > 2 * cap (b .buf ) {
63
+ if size > cap (b .buf )* 2 {
64
64
newBuf := make ([]byte , size )
65
65
copy (newBuf , b .buf )
66
66
b .buf = newBuf
67
67
return
68
68
}
69
69
70
- for cap (b .buf ) < size {
71
- b .buf = append (b .buf [:cap (b .buf )], 0 )
70
+ for {
71
+ b .buf = append (b .buf , 0 )
72
+ b .buf = b .buf [:cap (b .buf )]
73
+
74
+ if cap (b .buf ) < size {
75
+ continue
76
+ }
77
+ return
72
78
}
73
- b .buf = b .buf [:cap (b .buf )]
74
79
}
75
80
76
81
// returns next N bytes from buffer.
You can’t perform that action at this time.
0 commit comments