mirror of
https://github.com/nspcc-dev/neo-go.git
synced 2024-12-23 13:41:37 +00:00
network: fix compression handling functions
Turns out, Neo uses block compression and not a streaming lz4 format. And it doesn't contain uncompressed payload size which makes guessing it somewhat suboptimal.
This commit is contained in:
parent
8388e509df
commit
dde0763840
1 changed files with 10 additions and 14 deletions
|
@ -1,33 +1,29 @@
|
||||||
package network
|
package network
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/pierrec/lz4"
|
"github.com/pierrec/lz4"
|
||||||
)
|
)
|
||||||
|
|
||||||
// compress compresses bytes using lz4.
|
// compress compresses bytes using lz4.
|
||||||
func compress(source []byte) ([]byte, error) {
|
func compress(source []byte) ([]byte, error) {
|
||||||
dest := new(bytes.Buffer)
|
dest := make([]byte, lz4.CompressBlockBound(len(source)))
|
||||||
w := lz4.NewWriter(dest)
|
size, err := lz4.CompressBlock(source, dest, nil)
|
||||||
_, err := io.Copy(w, bytes.NewReader(source))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if w.Close() != nil {
|
return dest[:size], nil
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return dest.Bytes(), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// decompress decompresses bytes using lz4.
|
// decompress decompresses bytes using lz4.
|
||||||
func decompress(source []byte) ([]byte, error) {
|
func decompress(source []byte) ([]byte, error) {
|
||||||
dest := new(bytes.Buffer)
|
maxSize := len(source) * 255
|
||||||
r := lz4.NewReader(bytes.NewReader(source))
|
if maxSize > PayloadMaxSize {
|
||||||
_, err := io.Copy(dest, r)
|
maxSize = PayloadMaxSize
|
||||||
|
}
|
||||||
|
dest := make([]byte, maxSize)
|
||||||
|
size, err := lz4.UncompressBlock(source, dest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return dest.Bytes(), nil
|
return dest[:size], nil
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue