trpc.group/trpc-go/trpc-go@v1.0.3/codec/compress.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  	"errors"
    18  )
    19  
    20  // Compressor is body compress and decompress interface.
    21  type Compressor interface {
    22  	Compress(in []byte) (out []byte, err error)
    23  	Decompress(in []byte) (out []byte, err error)
    24  }
    25  
    26  // CompressType is the mode of body compress or decompress.
    27  const (
    28  	CompressTypeNoop = iota
    29  	CompressTypeGzip
    30  	CompressTypeSnappy
    31  	CompressTypeZlib
    32  	CompressTypeStreamSnappy
    33  	CompressTypeBlockSnappy
    34  )
    35  
    36  var compressors = make(map[int]Compressor)
    37  
    38  // RegisterCompressor register a specific compressor, which will
    39  // be called by init function defined in third package.
    40  func RegisterCompressor(compressType int, s Compressor) {
    41  	compressors[compressType] = s
    42  }
    43  
    44  // GetCompressor returns a specific compressor by type.
    45  func GetCompressor(compressType int) Compressor {
    46  	return compressors[compressType]
    47  }
    48  
    49  // Compress returns the compressed data, the data is compressed
    50  // by a specific compressor.
    51  func Compress(compressorType int, in []byte) ([]byte, error) {
    52  	// Explicitly check for noop to avoid accessing the map.
    53  	if compressorType == CompressTypeNoop {
    54  		return in, nil
    55  	}
    56  	if len(in) == 0 {
    57  		return nil, nil
    58  	}
    59  	compressor := GetCompressor(compressorType)
    60  	if compressor == nil {
    61  		return nil, errors.New("compressor not registered")
    62  	}
    63  	return compressor.Compress(in)
    64  }
    65  
    66  // Decompress returns the decompressed data, the data is decompressed
    67  // by a specific compressor.
    68  func Decompress(compressorType int, in []byte) ([]byte, error) {
    69  	// Explicitly check for noop to avoid accessing the map.
    70  	if compressorType == CompressTypeNoop {
    71  		return in, nil
    72  	}
    73  	if len(in) == 0 {
    74  		return nil, nil
    75  	}
    76  	compressor := GetCompressor(compressorType)
    77  	if compressor == nil {
    78  		return nil, errors.New("compressor not registered")
    79  	}
    80  	return compressor.Decompress(in)
    81  }