trpc.group/trpc-go/trpc-go@v1.0.3/codec/compress_zlib.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package codec
    15  
    16  import (
    17  	"bytes"
    18  	"compress/zlib"
    19  	"io"
    20  )
    21  
    22  func init() {
    23  	RegisterCompressor(CompressTypeZlib, &ZlibCompress{})
    24  }
    25  
    26  // ZlibCompress is zlib compressor.
    27  type ZlibCompress struct {
    28  }
    29  
    30  // Compress returns binary data compressed by zlib.
    31  func (c *ZlibCompress) Compress(in []byte) ([]byte, error) {
    32  	if len(in) == 0 {
    33  		return in, nil
    34  	}
    35  	var (
    36  		buffer bytes.Buffer
    37  		out    []byte
    38  	)
    39  	writer := zlib.NewWriter(&buffer)
    40  	if _, err := writer.Write(in); err != nil {
    41  		writer.Close()
    42  		return out, err
    43  	}
    44  	if err := writer.Close(); err != nil {
    45  		return out, err
    46  	}
    47  	return buffer.Bytes(), nil
    48  }
    49  
    50  // Decompress returns binary data decompressed by zlib.
    51  func (c *ZlibCompress) Decompress(in []byte) ([]byte, error) {
    52  	if len(in) == 0 {
    53  		return in, nil
    54  	}
    55  	reader, err := zlib.NewReader(bytes.NewReader(in))
    56  	if err != nil {
    57  		var out []byte
    58  		return out, err
    59  	}
    60  	defer reader.Close()
    61  	return io.ReadAll(reader)
    62  }