Decompress stream based on content and transfer encoding headers.
16532
function decompressStream(stream, headers) {
  const transferEncoding  = headers.get('Transfer-Encoding');
  const contentEncoding   = headers.get('Content-Encoding');
  if (contentEncoding === 'deflate' || transferEncoding === 'deflate')
    return stream.pipe( Zlib.createInflate() );
  if (contentEncoding === 'gzip' || transferEncoding === 'gzip')
    return stream.pipe( Zlib.createGunzip() );
  return stream;
}
1220921
public static InputStream decompress(final InputStream in, final String fileName) throws IOException
  {
    if (fileName.endsWith(GZ_SUFFIX)) {
      return gzipInputStream(in);
    } else if (fileName.endsWith(BZ2_SUFFIX)) {
      return new BZip2CompressorInputStream(in, true);
    } else if (fileName.endsWith(XZ_SUFFIX)) {
      return new XZCompressorInputStream(in, true);
    } else if (fileName.endsWith(SNAPPY_SUFFIX)) {
      return new FramedSnappyCompressorInputStream(in);
    } else if (fileName.endsWith(ZSTD_SUFFIX)) {
      return new ZstdCompressorInputStream(in);
    } else if (fileName.endsWith(ZIP_SUFFIX)) {
      // This reads the first file in the archive.
      final ZipInputStream zipIn = new ZipInputStream(in, StandardCharsets.UTF_8);
      try {
        final ZipEntry nextEntry = zipIn.getNextEntry();
        if (nextEntry == null) {
          zipIn.close();

          // No files in the archive - return an empty stream.
          return new ByteArrayInputStream(new byte[0]);
        }
        return zipIn;
      }
      catch (IOException e) {
        try {
          zipIn.close();
        }
        catch (IOException e2) {
          e.addSuppressed(e2);
        }
        throw e;
      }
    } else {
      return in;
    }
  }
463673
def _compress_content(self, content):
        """"""
        zbuf = StringIO()
        zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
        zfile.write(content.read())
        zfile.close()
        content.file = zbuf
        return content
1248044
def encoding(self):
        """"""
        encoding = None
        ct = self.get_header('content-type')
        if ct:
            ah = AcceptHeader(ct)
            if ah.media_types:
                encoding = ah.media_types[0][2].get("charset", None)

        return encoding
437125
def decompress(ctype, unc_len, data):
    
    if ctype == UBIFS_COMPR_LZO:
        try:
            return lzo.decompress(b''.join((b'\xf0', struct.pack('>I', unc_len), data)))
        except Exception as e:
            error(decompress, 'Warn', 'LZO Error: %s' % e)
    elif ctype == UBIFS_COMPR_ZLIB:
        try:
            return zlib.decompress(data, -11)
        except Exception as e:
            error(decompress, 'Warn', 'ZLib Error: %s' % e)
    else:
        return data
1132309
def stream_gzip_decompress_lines(stream):
    
    dec = zlib.decompressobj(zlib.MAX_WBITS | 16)
    previous = ""
    for compressed_chunk in stream:
        chunk = dec.decompress(compressed_chunk).decode()
        if chunk:
            lines = (previous + chunk).split("\n")
            previous = lines.pop()
            for line in lines:
                yield line
    yield previous
552787
def decompress(self, data):
        
        chunks = []

        available_in = ffi.new("size_t *", len(data))
        in_buffer = ffi.new("uint8_t[]", data)
        next_in = ffi.new("uint8_t **", in_buffer)

        while True:
            # Allocate a buffer that's hopefully overlarge, but if it's not we
            # don't mind: we'll spin around again.
            buffer_size = 5 * len(data)
            available_out = ffi.new("size_t *", buffer_size)
            out_buffer = ffi.new("uint8_t[]", buffer_size)
            next_out = ffi.new("uint8_t **", out_buffer)

            rc = lib.BrotliDecoderDecompressStream(self._decoder,
                                                   available_in,
                                                   next_in,
                                                   available_out,
                                                   next_out,
                                                   ffi.NULL)

            # First, check for errors.
            if rc == lib.BROTLI_DECODER_RESULT_ERROR:
                error_code = lib.BrotliDecoderGetErrorCode(self._decoder)
                error_message = lib.BrotliDecoderErrorString(error_code)
                raise Error(
                    "Decompression error: %s" % ffi.string(error_message)
                )

            # Next, copy the result out.
            chunk = ffi.buffer(out_buffer, buffer_size - available_out[0])[:]
            chunks.append(chunk)

            if rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
                assert available_in[0] == 0
                break
            elif rc == lib.BROTLI_DECODER_RESULT_SUCCESS:
                break
            else:
                # It's cool if we need more output, we just loop again.
                assert rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT

        return b''.join(chunks)
915466
def smart_content_encoding(self):
        """"""
        encoding = self.content_encoding
        if not encoding:
            base_list = self.basename.split('.')
            while (not encoding) and len(base_list) > 1:
                _, encoding = mimetypes.guess_type('.'.join(base_list))
                base_list.pop()

        return encoding
146001
def FromEncoded(self, encoded):
        

        stream_type = (encoded >> 12) & 0b1111
        stream_system = bool(encoded & (1 << 11))
        stream_id = (encoded & ((1 << 11) - 1))

        return DataStream(stream_type, stream_id, stream_system)
394848
public T decode(ProtoHead head, InputStream in, Charset charset) throws IOException {
        this.head = head;
        return decodeContent(in, charset);
    }
465120
def load(self, encoding='utf8', encoding_errors='ignore'):  # pylint: disable=arguments-differ
        
        if isinstance(self.codec, codec.NoCodec) and \
           self.fs.load_text != FileSystem.load_text:
            stream = self.fs.load_text(encoding, encoding_errors)
        else:
            stream = self.fs.load()
            stream = self.codec.decompress(stream)
            stream = TextIOWrapper(stream, encoding, encoding_errors)
        return stream
311995
function convertToCompressedRequest(req, res, compression) {
        var type = mime.lookup(req.path);
        var charset = mime.charsets.lookup(type);
        var search = req.url.split('?').splice(1).join('?');

        if (search !== "") {
            search = "?" + search;
        }

        req.url = req.path + compression.fileExtension + search;
        res.setHeader("Content-Encoding", compression.encodingName);
        res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : ""));
    }
659222
def gzip(f, *args, **kwargs):
    """"""

    data = f(*args, **kwargs)

    if isinstance(data, Response):
        content = data.data
    else:
        content = data

    gzip_buffer = BytesIO()
    gzip_file = gzip2.GzipFile(
        mode='wb',
        compresslevel=4,
        fileobj=gzip_buffer
    )
    gzip_file.write(content)
    gzip_file.close()

    gzip_data = gzip_buffer.getvalue()

    if isinstance(data, Response):
        data.data = gzip_data
        data.headers['Content-Encoding'] = 'gzip'
        data.headers['Content-Length'] = str(len(data.data))

        return data

    return gzip_data
680702
def decompress(self, data):
		""""""

		decompressed = ""
		pos = 0
		while pos < len(data):
			currentChar = data[pos]
			if currentChar != self.referencePrefix:
				decompressed += currentChar
				pos += 1
			else:
				nextChar = data[pos + 1]
				if nextChar != self.referencePrefix:
					distance = self.__decodeReferenceInt(data[pos + 1 : pos + 3], 2)
					length = self.__decodeReferenceLength(data[pos + 3])
					start = len(decompressed) - distance - length
					end = start + length
					decompressed += decompressed[start : end]
					pos += self.minStringLength - 1
				else:
					decompressed += self.referencePrefix
					pos += 2

		return decompressed
59302
public static void decompressString(InputStream inputStream, OutputStream outputStream) throws IOException {
        try (InputStream bufferedInputStream = new BufferedInputStream(inputStream);
             PrintWriter printWriter = new PrintWriter(outputStream);) {
            byte[] buffer = new byte[BYTES_BUFFER_SIZE];
            int len;
            while ((len = bufferedInputStream.read(buffer)) > 0) {
                String val = new String(buffer, StandardCharsets.UTF_8);
                String str = decompressString(val);
                printWriter.write(str);
            }
        }
    }
65359
public void decompress(ByteBuffer src, ByteBuffer dest) {
    final int destLen = getDecompressedLength(src, src.position());
    final int read = decompressor.decompress(src, src.position() + 4, dest, dest.position(), destLen);
    src.position(src.position() + 4 + read);
    dest.position(dest.position() + destLen);
  }
799182
def update_content_encoding(self, data: Any) -> None:
        """"""
        if not data:
            return

        enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower()
        if enc:
            if self.compress:
                raise ValueError(
                    'compress can not be set '
                    'if Content-Encoding header is set')
        elif self.compress:
            if not isinstance(self.compress, str):
                self.compress = 'deflate'
            self.headers[hdrs.CONTENT_ENCODING] = self.compress
            self.chunked = True