This repository has been archived by the owner on May 18, 2022. It is now read-only.
/
snappy.go
87 lines (67 loc) · 2.31 KB
/
snappy.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
package shrink
import (
"bytes"
"io/ioutil"
"github.com/dave/jennifer/jen"
"github.com/golang/snappy"
"github.com/koshatul/goembed/goembed"
"github.com/sirupsen/logrus"
)
// SnappyShrinker is a Shrinker compatible struct that uses snappy compression.
type SnappyShrinker struct {
}
// NewSnappyShrinker returns a Shrinker compatible class that uses snappy compression.
func NewSnappyShrinker() Shrinker {
return &SnappyShrinker{}
}
// Name returns a simple name for this module.
func (b *SnappyShrinker) Name() string {
return "snappy"
}
// IsStream returns true if the shrinker works on streams instead of byte slices.
func (b *SnappyShrinker) IsStream() bool {
return false
}
// IsReaderWithError returns true if the shrinker uses a reader that also can error.
func (b *SnappyShrinker) IsReaderWithError() bool {
return false
}
// Compress returns a byte array of compressed file data.
func (b *SnappyShrinker) Compress(file goembed.File) ([]jen.Code, error) {
v := []jen.Code{}
src, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
encoded := snappy.Encode(nil, src)
cmpOut := bytes.NewBuffer(encoded)
logrus.WithField("compression", "snappy").Debugf("Copied %d bytes into compressor", len(src))
buf := make([]byte, 1)
for {
if _, err := cmpOut.Read(buf); err != nil {
break
}
v = append(v, jen.Lit(int(buf[0])))
}
logrus.WithField("compression", "snappy").Debugf("Wrote %d bytes to static asset", len(v))
return v, nil
}
// Decompressor returns the body code for the `decode(input)` function.
func (b *SnappyShrinker) Decompressor() []jen.Code {
return []jen.Code{
jen.List(jen.Id("o"), jen.Id("_")).Op(":=").Qual("github.com/golang/snappy", "Decode").Call(jen.Nil(), jen.Id("input")),
jen.Return(jen.Id("o")),
}
}
// Reader returns the stream handler for the byte stream used when returning `Open()`.
func (b *SnappyShrinker) Reader(params ...jen.Code) jen.Code {
return jen.Qual("bytes", "NewReader").Params(jen.Id("decode").Call(params...))
}
// ReaderWithError returns the stream handler for the byte stream used when returning `Open()` but also returns an error.
func (b *SnappyShrinker) ReaderWithError(params ...jen.Code) jen.Code {
return nil
}
// Header returns additional code that is inserted in the body.
func (b *SnappyShrinker) Header() []jen.Code {
return []jen.Code{}
}