github.com/creachadair/ffs@v0.17.3/storage/codecs/zlib/zlib.go (about)

     1  // Copyright 2019 Michael J. Fromberger. All Rights Reserved.
     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 zlib implements the encoded.Codec interface to apply zlib
    16  // compression to blobs.
    17  package zlib
    18  
    19  import (
    20  	"bytes"
    21  	"compress/flate"
    22  	"compress/zlib"
    23  	"io"
    24  )
    25  
    26  // A Codec implements the encoded.Codec interface to provide zlib compression
    27  // of blob data. A zero value is ready for use, but performs no compression.
    28  // For most uses prefer NewCodec.
    29  type Codec struct{ level Level }
    30  
    31  // Level determines the compression level to use.
    32  type Level int
    33  
    34  // Compression level constants forwarded from compress/flate.
    35  const (
    36  	LevelNone     Level = flate.NoCompression
    37  	LevelFastest  Level = flate.BestSpeed
    38  	LevelSmallest Level = flate.BestCompression
    39  	LevelDefault  Level = flate.DefaultCompression
    40  )
    41  
    42  // NewCodec returns a Codec using the specified compression level.
    43  // Note that a zero level means no compression, not default compression.
    44  func NewCodec(level Level) Codec { return Codec{level} }
    45  
    46  // Encode compresses src via zlib and writes it to w.
    47  func (c Codec) Encode(w io.Writer, src []byte) error {
    48  	z, err := zlib.NewWriterLevel(w, int(c.level))
    49  	if err != nil {
    50  		return err
    51  	}
    52  	_, err = z.Write(src)
    53  	cerr := z.Close()
    54  	if err != nil {
    55  		return err
    56  	}
    57  	return cerr
    58  }
    59  
    60  // Decode decompresses src via zlib and writes it to w.
    61  func (c Codec) Decode(w io.Writer, src []byte) error {
    62  	z, err := zlib.NewReader(bytes.NewReader(src))
    63  	if err != nil {
    64  		return err
    65  	}
    66  	defer z.Close()
    67  	_, err = io.Copy(w, z)
    68  	return err
    69  }