-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathalgo.go
120 lines (97 loc) · 2.44 KB
/
algo.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package compress
import (
"io"
"io/ioutil"
"sync"
)
/*
gin-compress Copyright (C) 2022 Aurora McGinnis
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// algorithmConfig specifies options for a given compression algorithm
type algorithmConfig struct {
// enable indicates whether or not this compressor should be used
enable bool
// compressLevel is passed to the encoder object
compressLevel int
// priority indicates which algorithm will be selected when the client accepts multiple algorithms with equal q values
priority int
}
type algorithm interface {
// returns a compressor for this algorithm
getWriter(w io.Writer) io.WriteCloser
// returns a decompressor for this algorithm
getReader(r io.Reader) io.ReadCloser
// returns a pointer to the configuration struct
getConfig() *algorithmConfig
}
// algoritms contains the supported algorithms
var algorithms = map[string]algorithm{
ZSTD: newAlgorithmZstd(),
GZIP: newAlgorithmGzip(),
BROTLI: newAlgorithmBrotli(),
DEFLATE: newAlgorithmDeflate(),
}
func getEnabledAlgorithms() map[string]algorithm {
algos := make(map[string]algorithm, len(algorithms))
for k, v := range algorithms {
if v.getConfig().enable {
algos[k] = v
}
}
return algos
}
/*
The resettable* and wrapped* types are used to handle re-using writers/readers that support it
while still presenting a WriteCloser/ReadCloser interface
*/
type resettableCompressor interface {
io.WriteCloser
Reset(w io.Writer)
}
type resettableDecompressor interface {
io.Reader
Reset(r io.Reader) error
}
type wrappedWriter struct {
w resettableCompressor
p *sync.Pool
c bool
}
func (w *wrappedWriter) Write(b []byte) (int, error) {
if w.c {
panic("attempted to write to a closed writer")
}
return w.w.Write(b)
}
func (w *wrappedWriter) Close() error {
if w.c {
panic("attempted to close a compressor that has already been closed")
}
w.c = true
defer w.p.Put(w.w)
defer w.w.Reset(ioutil.Discard)
return w.w.Close()
}
type wrappedReader struct {
r resettableDecompressor
p *sync.Pool
c bool
}
func (r *wrappedReader) Read(b []byte) (int, error) {
if r.c {
panic("attempted to read from a closed reader")
}
return r.r.Read(b)
}
func (r *wrappedReader) Close() error {
if r.c {
return nil
}
r.c = true
defer r.p.Put(r.r)
r.r.Reset(nil)
return nil
}