forked from lestrrat-go/jwx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompress.go
41 lines (34 loc) · 883 Bytes
/
compress.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
package jwe
import (
"bytes"
"compress/flate"
"io/ioutil"
"github.com/lestrrat-go/jwx/internal/pool"
"github.com/lestrrat-go/jwx/jwa"
"github.com/pkg/errors"
)
func uncompress(plaintext []byte) ([]byte, error) {
return ioutil.ReadAll(flate.NewReader(bytes.NewReader(plaintext)))
}
func compress(plaintext []byte, alg jwa.CompressionAlgorithm) ([]byte, error) {
if alg == jwa.NoCompress {
return plaintext, nil
}
buf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(buf)
w, _ := flate.NewWriter(buf, 1)
in := plaintext
for len(in) > 0 {
n, err := w.Write(in)
if err != nil {
return nil, errors.Wrap(err, `failed to write to compression writer`)
}
in = in[n:]
}
if err := w.Close(); err != nil {
return nil, errors.Wrap(err, "failed to close compression writer")
}
ret := make([]byte, buf.Len())
copy(ret, buf.Bytes())
return ret, nil
}