-
Notifications
You must be signed in to change notification settings - Fork 660
/
gzip_compressor.go
90 lines (71 loc) · 2.09 KB
/
gzip_compressor.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
82
83
84
85
86
87
88
89
90
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package compression
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"sync"
"github.com/ava-labs/avalanchego/utils"
)
var _ Compressor = &gzipCompressor{}
type gzipCompressor struct {
maxSize int64
lock sync.Mutex
writeBuffer *bytes.Buffer
gzipWriter *gzip.Writer
bytesReader *bytes.Reader
gzipReader *gzip.Reader
}
// Compress [msg] and returns the compressed bytes.
func (g *gzipCompressor) Compress(msg []byte) ([]byte, error) {
if int64(len(msg)) > g.maxSize {
return nil, fmt.Errorf("msg length (%d) > maximum msg length (%d)", len(msg), g.maxSize)
}
g.lock.Lock()
defer g.lock.Unlock()
g.writeBuffer.Reset()
g.gzipWriter.Reset(g.writeBuffer)
if _, err := g.gzipWriter.Write(msg); err != nil {
return nil, err
}
if err := g.gzipWriter.Close(); err != nil {
return nil, err
}
compressed := g.writeBuffer.Bytes()
compressedCopy := utils.CopyBytes(compressed)
return compressedCopy, nil
}
// Decompress decompresses [msg].
func (g *gzipCompressor) Decompress(msg []byte) ([]byte, error) {
g.lock.Lock()
defer g.lock.Unlock()
g.bytesReader.Reset(msg)
if err := g.gzipReader.Reset(g.bytesReader); err != nil {
return nil, err
}
// We allow [io.LimitReader] to read up to [g.maxSize + 1] bytes, so that if
// the decompressed payload is greater than the maximum size, this function
// will return the appropriate error instead of an incomplete byte slice.
limitedReader := io.LimitReader(g.gzipReader, g.maxSize+1)
decompressed, err := io.ReadAll(limitedReader)
if err != nil {
return nil, err
}
if int64(len(decompressed)) > g.maxSize {
return nil, fmt.Errorf("msg length > maximum msg length (%d)", g.maxSize)
}
return decompressed, g.gzipReader.Close()
}
// NewGzipCompressor returns a new gzip Compressor that compresses
func NewGzipCompressor(maxSize int64) Compressor {
var buf bytes.Buffer
return &gzipCompressor{
maxSize: maxSize,
writeBuffer: &buf,
gzipWriter: gzip.NewWriter(&buf),
bytesReader: &bytes.Reader{},
gzipReader: &gzip.Reader{},
}
}