github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/compress/compress.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package compress
    16  
    17  import (
    18  	"github.com/golang/snappy"
    19  )
    20  
    21  const (
    22  	CompressTypeNo int = 0 + iota
    23  	CompressTypeSnappy
    24  )
    25  
    26  type Compressor interface {
    27  	Encode(dst, src []byte) []byte
    28  	Decode(dst, src []byte) ([]byte, error)
    29  	Type() int
    30  }
    31  
    32  var (
    33  	NoCompressor     noCompressor
    34  	SnappyCompressor snappyCompressor
    35  )
    36  
    37  func SetCompressor(t int) Compressor {
    38  	switch t {
    39  	case CompressTypeSnappy:
    40  		return SnappyCompressor
    41  	default:
    42  		return NoCompressor
    43  	}
    44  }
    45  
    46  type noCompressor struct{}
    47  
    48  func (c noCompressor) Encode(dst, src []byte) []byte {
    49  	return src
    50  }
    51  
    52  func (c noCompressor) Decode(dst, src []byte) ([]byte, error) {
    53  	return src, nil
    54  }
    55  
    56  func (c noCompressor) Type() int {
    57  	return CompressTypeNo
    58  }
    59  
    60  type snappyCompressor struct{}
    61  
    62  func (sc snappyCompressor) Encode(dst, src []byte) []byte {
    63  	return snappy.Encode(dst, src)
    64  }
    65  
    66  func (sc snappyCompressor) Decode(dst, src []byte) ([]byte, error) {
    67  	return snappy.Decode(dst, src)
    68  }
    69  
    70  func (sc snappyCompressor) Type() int {
    71  	return CompressTypeSnappy
    72  }