compression.go 2.1 KB

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