snappy.go 796 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package sarama
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "github.com/golang/snappy"
  6. )
  7. var snappyMagic = []byte{130, 83, 78, 65, 80, 80, 89, 0}
  8. // SnappyEncode encodes binary data
  9. func snappyEncode(src []byte) []byte {
  10. return snappy.Encode(nil, src)
  11. }
  12. // SnappyDecode decodes snappy data
  13. func snappyDecode(src []byte) ([]byte, error) {
  14. if bytes.Equal(src[:8], snappyMagic) {
  15. var (
  16. pos = uint32(16)
  17. max = uint32(len(src))
  18. dst = make([]byte, 0, len(src))
  19. chunk []byte
  20. err error
  21. )
  22. for pos < max {
  23. size := binary.BigEndian.Uint32(src[pos : pos+4])
  24. pos += 4
  25. chunk, err = snappy.Decode(chunk, src[pos:pos+size])
  26. if err != nil {
  27. return nil, err
  28. }
  29. pos += size
  30. dst = append(dst, chunk...)
  31. }
  32. return dst, nil
  33. }
  34. return snappy.Decode(nil, src)
  35. }