snappy.go 870 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package snappy
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. master "github.com/golang/snappy"
  6. )
  7. var xerialHeader = []byte{130, 83, 78, 65, 80, 80, 89, 0}
  8. // Encode encodes data as snappy with no framing header.
  9. func Encode(src []byte) []byte {
  10. return master.Encode(nil, src)
  11. }
  12. // Decode decodes snappy data whether it is traditional unframed
  13. // or includes the xerial framing format.
  14. func Decode(src []byte) ([]byte, error) {
  15. if !bytes.Equal(src[:8], xerialHeader) {
  16. return master.Decode(nil, src)
  17. }
  18. var (
  19. pos = uint32(16)
  20. max = uint32(len(src))
  21. dst = make([]byte, 0, len(src))
  22. chunk []byte
  23. err error
  24. )
  25. for pos < max {
  26. size := binary.BigEndian.Uint32(src[pos : pos+4])
  27. pos += 4
  28. chunk, err = master.Decode(chunk, src[pos:pos+size])
  29. if err != nil {
  30. return nil, err
  31. }
  32. pos += size
  33. dst = append(dst, chunk...)
  34. }
  35. return dst, nil
  36. }