@@ -29,6 +29,8 @@ import (
2929
3030var zstdCompressionMagic = [4 ]byte {0x28 , 0xb5 , 0x2f , 0xfd }
3131
32+ const zstdCompressionLevel = zstd .BestSpeed
33+
3234// checkCanCompress checks if there is an proposal payload message and peers supporting compression
3335func checkCanCompress (request broadcastRequest , prio bool , peers []* wsPeer ) bool {
3436 canCompress := false
@@ -56,9 +58,14 @@ func checkCanCompress(request broadcastRequest, prio bool, peers []*wsPeer) bool
5658// zstdCompressMsg returns a concatenation of a tag and compressed data
5759func zstdCompressMsg (tbytes []byte , d []byte ) ([]byte , string ) {
5860 bound := zstd .CompressBound (len (d ))
61+ if bound < len (d ) {
62+ // although CompressBound allocated more than the src size, this is an implementation detail.
63+ // increase the buffer size to always have enough space for the raw data if compression fails.
64+ bound = len (d )
65+ }
5966 mbytesComp := make ([]byte , len (tbytes )+ bound )
6067 copy (mbytesComp , tbytes )
61- comp , err := zstd .Compress (mbytesComp [len (tbytes ):], d )
68+ comp , err := zstd .CompressLevel (mbytesComp [len (tbytes ):], d , zstdCompressionLevel )
6269 if err != nil {
6370 // fallback and reuse non-compressed original data
6471 logMsg := fmt .Sprintf ("failed to compress into buffer of len %d: %v" , len (d ), err )
0 commit comments