github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/network/compress.go (about) 1 package network 2 3 import ( 4 "encoding/binary" 5 "errors" 6 7 "github.com/nspcc-dev/neo-go/pkg/network/payload" 8 "github.com/pierrec/lz4" 9 ) 10 11 // compress compresses bytes using lz4. 12 func compress(source []byte) ([]byte, error) { 13 dest := make([]byte, 4+lz4.CompressBlockBound(len(source))) 14 size, err := lz4.CompressBlock(source, dest[4:], nil) 15 if err != nil { 16 return nil, err 17 } 18 binary.LittleEndian.PutUint32(dest[:4], uint32(len(source))) 19 return dest[:size+4], nil 20 } 21 22 // decompress decompresses bytes using lz4. 23 func decompress(source []byte) ([]byte, error) { 24 if len(source) < 4 { 25 return nil, errors.New("invalid compressed payload") 26 } 27 length := binary.LittleEndian.Uint32(source[:4]) 28 if length > payload.MaxSize { 29 return nil, errors.New("invalid uncompressed payload length") 30 } 31 dest := make([]byte, length) 32 size, err := lz4.UncompressBlock(source[4:], dest) 33 if err != nil { 34 return nil, err 35 } 36 if uint32(size) != length { 37 return nil, errors.New("decompressed payload size doesn't match header") 38 } 39 return dest, nil 40 }