blob: 5192b02733014492bf4c968d0698477f1a423efe [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001package diskv
2
3import (
4 "compress/flate"
5 "compress/gzip"
6 "compress/zlib"
7 "io"
8)
9
10// Compression is an interface that Diskv uses to implement compression of
11// data. Writer takes a destination io.Writer and returns a WriteCloser that
12// compresses all data written through it. Reader takes a source io.Reader and
13// returns a ReadCloser that decompresses all data read through it. You may
14// define these methods on your own type, or use one of the NewCompression
15// helpers.
16type Compression interface {
17 Writer(dst io.Writer) (io.WriteCloser, error)
18 Reader(src io.Reader) (io.ReadCloser, error)
19}
20
21// NewGzipCompression returns a Gzip-based Compression.
22func NewGzipCompression() Compression {
23 return NewGzipCompressionLevel(flate.DefaultCompression)
24}
25
26// NewGzipCompressionLevel returns a Gzip-based Compression with the given level.
27func NewGzipCompressionLevel(level int) Compression {
28 return &genericCompression{
29 wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) },
30 rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) },
31 }
32}
33
34// NewZlibCompression returns a Zlib-based Compression.
35func NewZlibCompression() Compression {
36 return NewZlibCompressionLevel(flate.DefaultCompression)
37}
38
39// NewZlibCompressionLevel returns a Zlib-based Compression with the given level.
40func NewZlibCompressionLevel(level int) Compression {
41 return NewZlibCompressionLevelDict(level, nil)
42}
43
44// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given
45// level, based on the given dictionary.
46func NewZlibCompressionLevelDict(level int, dict []byte) Compression {
47 return &genericCompression{
48 func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) },
49 func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) },
50 }
51}
52
53type genericCompression struct {
54 wf func(w io.Writer) (io.WriteCloser, error)
55 rf func(r io.Reader) (io.ReadCloser, error)
56}
57
58func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) {
59 return g.wf(dst)
60}
61
62func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) {
63 return g.rf(src)
64}