textencoder.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package matchfinder
  2. import "fmt"
  3. // A TextEncoder is an Encoder that produces a human-readable representation of
  4. // the LZ77 compression. Matches are replaced with <Length,Distance> symbols.
  5. type TextEncoder struct{}
  6. func (t TextEncoder) Reset() {}
  7. func (t TextEncoder) Encode(dst []byte, src []byte, matches []Match, lastBlock bool) []byte {
  8. pos := 0
  9. for _, m := range matches {
  10. if m.Unmatched > 0 {
  11. dst = append(dst, src[pos:pos+m.Unmatched]...)
  12. pos += m.Unmatched
  13. }
  14. if m.Length > 0 {
  15. dst = append(dst, []byte(fmt.Sprintf("<%d,%d>", m.Length, m.Distance))...)
  16. pos += m.Length
  17. }
  18. }
  19. if pos < len(src) {
  20. dst = append(dst, src[pos:]...)
  21. }
  22. return dst
  23. }
  24. // A NoMatchFinder implements MatchFinder, but doesn't find any matches.
  25. // It can be used to implement the equivalent of the standard library flate package's
  26. // HuffmanOnly setting.
  27. type NoMatchFinder struct{}
  28. func (n NoMatchFinder) Reset() {}
  29. func (n NoMatchFinder) FindMatches(dst []Match, src []byte) []Match {
  30. return append(dst, Match{
  31. Unmatched: len(src),
  32. })
  33. }
  34. // AutoReset wraps a MatchFinder that can return references to data in previous
  35. // blocks, and calls Reset before each block. It is useful for (e.g.) using a
  36. // snappy Encoder with a MatchFinder designed for flate. (Snappy doesn't
  37. // support references between blocks.)
  38. type AutoReset struct {
  39. MatchFinder
  40. }
  41. func (a AutoReset) FindMatches(dst []Match, src []byte) []Match {
  42. a.Reset()
  43. return a.MatchFinder.FindMatches(dst, src)
  44. }