File tree Expand file tree Collapse file tree 2 files changed +32
-4
lines changed Expand file tree Collapse file tree 2 files changed +32
-4
lines changed Original file line number Diff line number Diff line change @@ -90,8 +90,8 @@ func Encode(w io.Writer, val interface{}) error {
90
90
return outer .encode (val )
91
91
}
92
92
eb := encbufPool .Get ().(* encbuf )
93
- eb .reset ()
94
93
defer encbufPool .Put (eb )
94
+ eb .reset ()
95
95
if err := eb .encode (val ); err != nil {
96
96
return err
97
97
}
@@ -102,8 +102,8 @@ func Encode(w io.Writer, val interface{}) error {
102
102
// Please see the documentation of Encode for the encoding rules.
103
103
func EncodeToBytes (val interface {}) ([]byte , error ) {
104
104
eb := encbufPool .Get ().(* encbuf )
105
- eb .reset ()
106
105
defer encbufPool .Put (eb )
106
+ eb .reset ()
107
107
if err := eb .encode (val ); err != nil {
108
108
return nil , err
109
109
}
@@ -288,8 +288,13 @@ type encReader struct {
288
288
func (r * encReader ) Read (b []byte ) (n int , err error ) {
289
289
for {
290
290
if r .piece = r .next (); r .piece == nil {
291
- encbufPool .Put (r .buf )
292
- r .buf = nil
291
+ // Put the encode buffer back into the pool at EOF when it
292
+ // is first encountered. Subsequent calls still return EOF
293
+ // as the error but the buffer is no longer valid.
294
+ if r .buf != nil {
295
+ encbufPool .Put (r .buf )
296
+ r .buf = nil
297
+ }
293
298
return n , io .EOF
294
299
}
295
300
nn := copy (b [n :], r .piece )
Original file line number Diff line number Diff line change @@ -23,6 +23,7 @@ import (
23
23
"io"
24
24
"io/ioutil"
25
25
"math/big"
26
+ "sync"
26
27
"testing"
27
28
)
28
29
@@ -306,3 +307,25 @@ func TestEncodeToReaderPiecewise(t *testing.T) {
306
307
return output , nil
307
308
})
308
309
}
310
+
311
+ // This is a regression test verifying that encReader
312
+ // returns its encbuf to the pool only once.
313
+ func TestEncodeToReaderReturnToPool (t * testing.T ) {
314
+ buf := make ([]byte , 50 )
315
+ wg := new (sync.WaitGroup )
316
+ for i := 0 ; i < 5 ; i ++ {
317
+ wg .Add (1 )
318
+ go func () {
319
+ for i := 0 ; i < 1000 ; i ++ {
320
+ _ , r , _ := EncodeToReader ("foo" )
321
+ ioutil .ReadAll (r )
322
+ r .Read (buf )
323
+ r .Read (buf )
324
+ r .Read (buf )
325
+ r .Read (buf )
326
+ }
327
+ wg .Done ()
328
+ }()
329
+ }
330
+ wg .Wait ()
331
+ }
You can’t perform that action at this time.
0 commit comments