diff --git a/netcard.go b/netcard.go index 2b7f05e..493ab42 100644 --- a/netcard.go +++ b/netcard.go @@ -209,7 +209,8 @@ func (nt *NetTunnel) SendFrames(stream gen.FrameService_SendFramesServer) error log.Panic(err) } - nt.writer <- Decompress(request.GetFrames()) + buf, _ := Decompress(request.GetFrames()) + nt.writer <- buf // frames := Decompress(request.GetFrames()) // if len(frames) > 0 { diff --git a/rpc_client.go b/rpc_client.go index bfca908..8cecbf0 100644 --- a/rpc_client.go +++ b/rpc_client.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "context" "log" gen "slimming/proto/gen" @@ -102,7 +101,7 @@ func (cli *RPCClient) run() { // var ticker = time.NewTicker(time.Millisecond * 1) - buffer := bytes.NewBuffer(nil) + // buffer := bytes.NewBuffer(nil) for buf := range cli.Frames { // select { @@ -131,11 +130,9 @@ func (cli *RPCClient) run() { // continue // } - Compress(buffer, buf) - // 发到对面的网卡 err = stream.Send(&gen.RequestFrames{ - Frames: buffer.Bytes(), + Frames: Compress(buf), }) if err != nil { log.Panic(err) diff --git a/utils.go b/utils.go index 01b2692..15c6129 100644 --- a/utils.go +++ b/utils.go @@ -1,56 +1,28 @@ package main import ( - "bytes" "encoding/binary" - "io" - "log" "net" "github.com/klauspost/compress/zstd" ) -func Compress(writer io.Writer, data []byte) { - - // encode gob - // enc := gob.NewEncoder(writer) - // err := enc.Encode(data) - // if err != nil { - // log.Panic(err) - // } - - // zstd compress - zenc, err := zstd.NewWriter(writer) - if err != nil { - log.Panic(err) - } - zenc.Write(data) - err = zenc.Flush() - if err != nil { - log.Println(err) - } +var encoder, _ = zstd.NewWriter(nil) +// Compress a buffer. +// If you have a destination buffer, the allocation in the call can also be eliminated. +func Compress(src []byte) []byte { + return encoder.EncodeAll(src, make([]byte, 0, len(src))) } -func Decompress(data []byte) (frames []byte) { - var err error +// Create a reader that caches decompressors. +// For this operation type we supply a nil Reader. +var decoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0)) - var buf = bytes.NewBuffer(data) - var zdec *zstd.Decoder - zdec, err = zstd.NewReader(buf) - if err != nil { - log.Panic(err) - } - zdec.Close() - frames = buf.Bytes() - - // dec := gob.NewDecoder(buf) - // err = dec.Decode(&frames) - // if err != nil { - // log.Panic(err) - // } - - return +// Decompress a buffer. We don't supply a destination buffer, +// so it will be allocated by the decoder. +func Decompress(src []byte) ([]byte, error) { + return decoder.DecodeAll(src, nil) } func SwapBytes(frame1 []byte, start1 int, frame2 []byte, start2 int, size int) {