github.com/peterbourgon/diskv@v2.0.1+incompatible/compression.go (about) 1 package diskv 2 3 import ( 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. 16 type 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. 22 func NewGzipCompression() Compression { 23 return NewGzipCompressionLevel(flate.DefaultCompression) 24 } 25 26 // NewGzipCompressionLevel returns a Gzip-based Compression with the given level. 27 func 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. 35 func NewZlibCompression() Compression { 36 return NewZlibCompressionLevel(flate.DefaultCompression) 37 } 38 39 // NewZlibCompressionLevel returns a Zlib-based Compression with the given level. 40 func 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. 46 func 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 53 type genericCompression struct { 54 wf func(w io.Writer) (io.WriteCloser, error) 55 rf func(r io.Reader) (io.ReadCloser, error) 56 } 57 58 func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) { 59 return g.wf(dst) 60 } 61 62 func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) { 63 return g.rf(src) 64 }