/*
 *
 * Copyright 2017 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// Package gzip implements and registers the gzip compressor // during the initialization. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release.
package gzip import ( ) // Name is the name registered for the gzip compressor. const Name = "gzip" func init() { := &compressor{} .poolCompressor.New = func() any { return &writer{Writer: gzip.NewWriter(io.Discard), pool: &.poolCompressor} } encoding.RegisterCompressor() } type writer struct { *gzip.Writer pool *sync.Pool } // SetLevel updates the registered gzip compressor to use the compression level specified (gzip.HuffmanOnly is not supported). // NOTE: this function must only be called during initialization time (i.e. in an init() function), // and is not thread-safe. // // The error returned will be nil if the specified level is valid. func ( int) error { if < gzip.DefaultCompression || > gzip.BestCompression { return fmt.Errorf("grpc: invalid gzip compression level: %d", ) } := encoding.GetCompressor(Name).(*compressor) .poolCompressor.New = func() any { , := gzip.NewWriterLevel(io.Discard, ) if != nil { panic() } return &writer{Writer: , pool: &.poolCompressor} } return nil } func ( *compressor) ( io.Writer) (io.WriteCloser, error) { := .poolCompressor.Get().(*writer) .Writer.Reset() return , nil } func ( *writer) () error { defer .pool.Put() return .Writer.Close() } type reader struct { *gzip.Reader pool *sync.Pool } func ( *compressor) ( io.Reader) (io.Reader, error) { , := .poolDecompressor.Get().(*reader) if ! { , := gzip.NewReader() if != nil { return nil, } return &reader{Reader: , pool: &.poolDecompressor}, nil } if := .Reset(); != nil { .poolDecompressor.Put() return nil, } return , nil } func ( *reader) ( []byte) ( int, error) { , = .Reader.Read() if == io.EOF { .pool.Put() } return , } // RFC1952 specifies that the last four bytes "contains the size of // the original (uncompressed) input data modulo 2^32." // gRPC has a max message size of 2GB so we don't need to worry about wraparound. func ( *compressor) ( []byte) int { := len() if < 4 { return -1 } return int(binary.LittleEndian.Uint32([-4 : ])) } func ( *compressor) () string { return Name } type compressor struct { poolCompressor sync.Pool poolDecompressor sync.Pool }