go.chromium.org/luci@v0.0.0-20250314024836-d9a61d0730e6/tokenserver/appengine/impl/utils/zip.go (about)

     1  // Copyright 2016 The LUCI Authors.
     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 utils
    16  
    17  import (
    18  	"bytes"
    19  	"compress/zlib"
    20  	"io"
    21  )
    22  
    23  // ZlibCompress zips a blob using zlib.
    24  func ZlibCompress(in []byte) ([]byte, error) {
    25  	out := bytes.Buffer{}
    26  	w := zlib.NewWriter(&out)
    27  	_, writeErr := w.Write(in)
    28  	closeErr := w.Close()
    29  	if writeErr != nil {
    30  		return nil, writeErr
    31  	}
    32  	if closeErr != nil {
    33  		return nil, closeErr
    34  	}
    35  	return out.Bytes(), nil
    36  }
    37  
    38  // ZlibDecompress unzips a blob using zlib.
    39  func ZlibDecompress(in []byte) ([]byte, error) {
    40  	out := bytes.Buffer{}
    41  	r, err := zlib.NewReader(bytes.NewReader(in))
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	_, readErr := io.Copy(&out, r)
    46  	closeErr := r.Close()
    47  	if readErr != nil {
    48  		return nil, readErr
    49  	}
    50  	if closeErr != nil {
    51  		return nil, closeErr
    52  	}
    53  	return out.Bytes(), nil
    54  }