File tree Expand file tree Collapse file tree 1 file changed +21
-15
lines changed Expand file tree Collapse file tree 1 file changed +21
-15
lines changed Original file line number Diff line number Diff line change @@ -31,11 +31,14 @@ func newBuffer(rd io.Reader) *buffer {
31
31
}
32
32
}
33
33
34
- // fill reads at least _need_ bytes in the buffer
35
- // existing data in the buffer gets lost
34
+ // fill reads into the buffer until at least _need_ bytes are in it
36
35
func (b * buffer ) fill (need int ) (err error ) {
36
+ // move existing data to the beginning
37
+ if b .length > 0 && b .idx > 0 {
38
+ copy (b .buf [0 :b .length ], b .buf [b .idx :])
39
+ }
40
+
37
41
b .idx = 0
38
- b .length = 0
39
42
40
43
var n int
41
44
for b .length < need {
@@ -62,27 +65,30 @@ func (b *buffer) readNext(need int) (p []byte, err error) {
62
65
return
63
66
64
67
} else {
65
- p = make ([]byte , need )
66
- has := 0
67
-
68
- // copy data that is already in the buffer
69
- if b .length > 0 {
70
- copy (p [0 :b .length ], b .buf [b .idx :])
71
- has = b .length
72
- need -= has
73
- b .idx = 0
74
- b .length = 0
75
- }
76
68
77
69
// does the data fit into the buffer?
78
70
if need < len (b .buf ) {
71
+ // refill
79
72
err = b .fill (need ) // err deferred
80
- copy ( p [ has : has + need ], b .buf [b . idx :])
73
+ p = b .buf [: need ]
81
74
b .idx += need
82
75
b .length -= need
83
76
return
84
77
85
78
} else {
79
+ p = make ([]byte , need )
80
+ has := 0
81
+
82
+ // copy data that is already in the buffer
83
+ if b .length > 0 {
84
+ copy (p [0 :b .length ], b .buf [b .idx :])
85
+ has = b .length
86
+ need -= has
87
+ b .idx = 0
88
+ b .length = 0
89
+ }
90
+
91
+ // read rest directly into the new slice
86
92
var n int
87
93
for err == nil && need > 0 {
88
94
n , err = b .rd .Read (p [has :])
You can’t perform that action at this time.
0 commit comments