go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/auth_service/impl/util/zlib/codec.go (about) 1 // Copyright 2024 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 zlib contains functions for zlib encoding and decoding. 16 package zlib 17 18 import ( 19 "bytes" 20 "compress/zlib" 21 "io" 22 ) 23 24 func Compress(input []byte) ([]byte, error) { 25 var b bytes.Buffer 26 w := zlib.NewWriter(&b) 27 if _, err := w.Write(input); err != nil { 28 // Error writing; close the writer before returning. 29 _ = w.Close() 30 return nil, err 31 } 32 33 if err := w.Close(); err != nil { 34 // Error closing writer. 35 return nil, err 36 } 37 38 return b.Bytes(), nil 39 } 40 41 func Decompress(input []byte) ([]byte, error) { 42 r, err := zlib.NewReader(bytes.NewBuffer(input)) 43 if err != nil { 44 // Error creating reader. 45 return nil, err 46 } 47 48 w := bytes.NewBuffer([]byte{}) 49 if _, err := io.Copy(w, r); err != nil { 50 // Error copying from reader; close the reader before returning. 51 _ = r.Close() 52 return nil, err 53 } 54 55 if err := r.Close(); err != nil { 56 // Error closing the reader. 57 return nil, err 58 } 59 60 return w.Bytes(), nil 61 }