| 1 |
package sync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"compress/zlib" |
| 6 |
"io" |
| 7 |
"sync" |
| 8 |
) |
| 9 |
|
| 10 |
var ( |
| 11 |
zlibInitBytes = []byte{0x78, 0x9c, 0x01, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01} |
| 12 |
zlibReader = sync.Pool{ |
| 13 |
New: func() interface{} { |
| 14 |
r, _ := zlib.NewReader(bytes.NewReader(zlibInitBytes)) |
| 15 |
return ZLibReader{ |
| 16 |
Reader: r.(zlibReadCloser), |
| 17 |
} |
| 18 |
}, |
| 19 |
} |
| 20 |
zlibWriter = sync.Pool{ |
| 21 |
New: func() interface{} { |
| 22 |
return zlib.NewWriter(nil) |
| 23 |
}, |
| 24 |
} |
| 25 |
) |
| 26 |
|
| 27 |
type zlibReadCloser interface { |
| 28 |
io.ReadCloser |
| 29 |
zlib.Resetter |
| 30 |
} |
| 31 |
|
| 32 |
type ZLibReader struct { |
| 33 |
dict *[]byte |
| 34 |
Reader zlibReadCloser |
| 35 |
} |
| 36 |
|
| 37 |
// GetZlibReader returns a ZLibReader that is managed by a sync.Pool. |
| 38 |
// Returns a ZLibReader that is reset using a dictionary that is |
| 39 |
// also managed by a sync.Pool. |
| 40 |
// |
| 41 |
// After use, the ZLibReader should be put back into the sync.Pool |
| 42 |
// by calling PutZlibReader. |
| 43 |
func GetZlibReader(r io.Reader) (ZLibReader, error) { |
| 44 |
z := zlibReader.Get().(ZLibReader) |
| 45 |
z.dict = GetByteSlice() |
| 46 |
|
| 47 |
err := z.Reader.Reset(r, *z.dict) |
| 48 |
|
| 49 |
return z, err |
| 50 |
} |
| 51 |
|
| 52 |
// PutZlibReader puts z back into its sync.Pool, first closing the reader. |
| 53 |
// The Byte slice dictionary is also put back into its sync.Pool. |
| 54 |
func PutZlibReader(z ZLibReader) { |
| 55 |
z.Reader.Close() |
| 56 |
PutByteSlice(z.dict) |
| 57 |
zlibReader.Put(z) |
| 58 |
} |
| 59 |
|
| 60 |
// GetZlibWriter returns a *zlib.Writer that is managed by a sync.Pool. |
| 61 |
// Returns a writer that is reset with w and ready for use. |
| 62 |
// |
| 63 |
// After use, the *zlib.Writer should be put back into the sync.Pool |
| 64 |
// by calling PutZlibWriter. |
| 65 |
func GetZlibWriter(w io.Writer) *zlib.Writer { |
| 66 |
z := zlibWriter.Get().(*zlib.Writer) |
| 67 |
z.Reset(w) |
| 68 |
return z |
| 69 |
} |
| 70 |
|
| 71 |
// PutZlibWriter puts w back into its sync.Pool. |
| 72 |
func PutZlibWriter(w *zlib.Writer) { |
| 73 |
zlibWriter.Put(w) |
| 74 |
} |