-
Notifications
You must be signed in to change notification settings - Fork 136
/
decompressor.go
81 lines (69 loc) · 1.9 KB
/
decompressor.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package compress
import (
"bytes"
"compress/zlib"
"io"
"github.com/pkg/errors"
)
// Decompressor is a fast, single threaded compressor.
// This type allows us to reuse buffers etc for performance
type Decompressor interface {
// Decompress decompresses the byte array
Decompress(b []byte) ([]byte, error)
}
// NoOpDecompressor is a DeCompressor that does nothing. Useful for tests.
type NoOpDecompressor struct{}
func (c *NoOpDecompressor) Decompress(b []byte) ([]byte, error) {
return b, nil
}
// ZlibDecompressor decompresses Zlib
type ZlibDecompressor struct {
outputBuffer *bytes.Buffer
inputBuffer *bytes.Buffer
reader io.ReadCloser
}
func NewZlibDecompressor() *ZlibDecompressor {
var ib bytes.Buffer
var ob bytes.Buffer
return &ZlibDecompressor{
inputBuffer: &ib,
outputBuffer: &ob,
}
}
func (d *ZlibDecompressor) Decompress(b []byte) ([]byte, error) {
inputBuffer := bytes.NewBuffer(b)
if d.reader == nil {
reader, err := zlib.NewReader(inputBuffer)
if err != nil {
return nil, errors.WithStack(err)
}
d.reader = reader
} else {
err := d.reader.(zlib.Resetter).Reset(inputBuffer, nil)
if err != nil {
return nil, errors.WithStack(err)
}
d.outputBuffer.Reset()
}
// Decompress
_, err := io.Copy(d.outputBuffer, d.reader)
if err != nil {
return nil, errors.WithStack(err)
}
decompressed := d.outputBuffer.Bytes()
return decompressed, nil
}
// ThreadSafeZlibDecompressor provides a thread safe decompressor, at the cost of instantiating a new ZlibDecompressor
// for each Decompress call
type ThreadSafeZlibDecompressor struct{}
func NewThreadSafeZlibDecompressor() *ThreadSafeZlibDecompressor {
return &ThreadSafeZlibDecompressor{}
}
func (d *ThreadSafeZlibDecompressor) Decompress(b []byte) ([]byte, error) {
decompressor := NewZlibDecompressor()
decompressed, err := decompressor.Decompress(b)
if err != nil {
return nil, err
}
return decompressed, nil
}