/
zlib.go
48 lines (37 loc) · 861 Bytes
/
zlib.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package compressors
import (
"bytes"
"fmt"
"io"
"sync"
"github.com/klauspost/compress/zlib"
)
type Zlib struct {
sync.Pool
}
func NewZlib(level int) *Zlib {
return &Zlib{sync.Pool{
New: func() interface{} {
writer, err := zlib.NewWriterLevel(&bytes.Buffer{}, level)
if err != nil {
panic("unreachable code")
}
return writer
},
}}
}
func (compressorPool *Zlib) Compress(target io.Writer, from *bytes.Buffer) error {
writer, ok := compressorPool.Get().(*zlib.Writer)
if !ok {
panic("unreachable code")
}
defer compressorPool.Put(writer)
writer.Reset(target)
if _, err := writer.Write(from.Bytes()); err != nil {
return fmt.Errorf("compressors: zlib: failed to write data: %w", err)
}
if err := writer.Flush(); err != nil {
return fmt.Errorf("compressors: zlib: failed to flush data: %w", err)
}
return nil
}