3 // Copyright 2015 Ernest Micklei. All rights reserved.
4 // Use of this source code is governed by a license
5 // that can be found in the LICENSE file.
14 // SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool.
15 type SyncPoolCompessors struct {
16 GzipWriterPool *sync.Pool
17 GzipReaderPool *sync.Pool
18 ZlibWriterPool *sync.Pool
21 // NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors.
22 func NewSyncPoolCompessors() *SyncPoolCompessors {
23 return &SyncPoolCompessors{
24 GzipWriterPool: &sync.Pool{
25 New: func() interface{} { return newGzipWriter() },
27 GzipReaderPool: &sync.Pool{
28 New: func() interface{} { return newGzipReader() },
30 ZlibWriterPool: &sync.Pool{
31 New: func() interface{} { return newZlibWriter() },
36 func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer {
37 return s.GzipWriterPool.Get().(*gzip.Writer)
40 func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer) {
41 s.GzipWriterPool.Put(w)
44 func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader {
45 return s.GzipReaderPool.Get().(*gzip.Reader)
48 func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader) {
49 s.GzipReaderPool.Put(r)
52 func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer {
53 return s.ZlibWriterPool.Get().(*zlib.Writer)
56 func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer) {
57 s.ZlibWriterPool.Put(w)
60 func newGzipWriter() *gzip.Writer {
61 // create with an empty bytes writer; it will be replaced before using the gzipWriter
62 writer, err := gzip.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed)
69 func newGzipReader() *gzip.Reader {
70 // create with an empty reader (but with GZIP header); it will be replaced before using the gzipReader
71 // we can safely use currentCompressProvider because it is set on package initialization.
72 w := currentCompressorProvider.AcquireGzipWriter()
73 defer currentCompressorProvider.ReleaseGzipWriter(w)
74 b := new(bytes.Buffer)
78 reader, err := gzip.NewReader(bytes.NewReader(b.Bytes()))
85 func newZlibWriter() *zlib.Writer {
86 writer, err := zlib.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed)