2020-05-25 07:09:21 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
2020-07-29 14:09:59 +00:00
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
|
2020-06-15 18:13:32 +00:00
|
|
|
"github.com/nspcc-dev/neo-go/pkg/network/payload"
|
2020-05-25 07:09:21 +00:00
|
|
|
"github.com/pierrec/lz4"
|
|
|
|
)
|
|
|
|
|
|
|
|
// compress compresses bytes using lz4.
|
|
|
|
func compress(source []byte) ([]byte, error) {
|
2020-07-29 14:09:59 +00:00
|
|
|
dest := make([]byte, 4+lz4.CompressBlockBound(len(source)))
|
|
|
|
size, err := lz4.CompressBlock(source, dest[4:], nil)
|
2020-05-25 07:09:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-07-29 14:09:59 +00:00
|
|
|
binary.LittleEndian.PutUint32(dest[:4], uint32(len(source)))
|
|
|
|
return dest[:size+4], nil
|
2020-05-25 07:09:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// decompress decompresses bytes using lz4.
|
|
|
|
func decompress(source []byte) ([]byte, error) {
|
2020-07-29 14:09:59 +00:00
|
|
|
length := binary.LittleEndian.Uint32(source[:4])
|
|
|
|
if length > payload.MaxSize {
|
|
|
|
return nil, errors.New("invalid uncompressed payload length")
|
2020-06-18 08:32:38 +00:00
|
|
|
}
|
2020-07-29 14:09:59 +00:00
|
|
|
dest := make([]byte, length)
|
|
|
|
size, err := lz4.UncompressBlock(source[4:], dest)
|
2020-05-25 07:09:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-06-18 08:32:38 +00:00
|
|
|
return dest[:size], nil
|
2020-05-25 07:09:21 +00:00
|
|
|
}
|