Inverse of _parse_header.

    >>> _encode_header('permessage-deflate',
    ...     {'client_max_window_bits': 15, 'client_no_context_takeover': None})
    'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
9755
def _encode_header(key: str, pdict: Dict[str, str]) -> str:
    
    if not pdict:
        return key
    out = [key]
    # Sort the parameters just to make it easy to test.
    for k, v in sorted(pdict.items()):
        if v is None:
            out.append(k)
        else:
            # TODO: quote if necessary.
            out.append("%s=%s" % (k, v))
    return "; ".join(out)
1023165
private int parseHeader(byte[] data) throws DataFormatException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Parsing gzip header; state=" + this.state);
        }
        int pos = 0;
        for (; pos < data.length && PARSE_STATE.DONE != this.state;) {
            byte b = data[pos++];
            if (PARSE_STATE.ID1 == this.state) {
                if ((byte) 0x1F != b) {
                    throw new DataFormatException("Invalid gzip header, first byte=" + b);
                }
                this.state = PARSE_STATE.ID2;
            } else if (PARSE_STATE.ID2 == this.state) {
                if ((byte) 0x8B != b) {
                    throw new DataFormatException("Invalid gzip header, second byte=" + b);
                }
                this.state = PARSE_STATE.COMPRESSION;
            } else if (PARSE_STATE.COMPRESSION == this.state) {
                if (Deflater.DEFLATED != b) {
                    throw new DataFormatException("Invalid gzip compression method=" + b);
                }
                this.state = PARSE_STATE.FLAG;
            } else if (PARSE_STATE.FLAG == this.state) {
                if (-1 == this.gzipFlag) {
                    // after saving the extra flag byte, skip the next 6 bytes
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "gzip header flag=" + b);
                    }
                    this.gzipFlag = b;
                    pos = skip(data, pos, 6);
                } else {
                    // previously saw the flag but didn't skip a full 6
                    pos = skip(data, pos, this.parseInt);
                }
                if (0 == this.parseInt) {
                    if (isFExtraSet()) {
                        this.state = PARSE_STATE.FEXTRA;
                    } else if (isFNameSet()) {
                        this.state = PARSE_STATE.FNAME;
                    } else if (isFCommentSet()) {
                        this.state = PARSE_STATE.FCOMMENT;
                    } else if (isFHCRCSet()) {
                        this.state = PARSE_STATE.FHCRC;
                    } else {
                        this.state = PARSE_STATE.DONE;
                    }
                    this.parseOffset = 0;
                }
            } else if (PARSE_STATE.FEXTRA == this.state) {
                // FEXTRA has length in 2 bytes, then that many bytes
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Parsing FEXTRA data, offset=" + this.parseOffset);
                }
                if (0 == this.parseOffset) {
                    this.parseInt = b;
                    this.parseOffset++;
                    continue;
                } else if (1 == this.parseOffset) {
                    this.parseInt = (b << 8) | this.parseInt;
                    this.parseOffset++;
                }
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "FEXTRA length is " + this.parseInt);
                }
                pos = skip(data, pos, this.parseInt);
                if (0 == this.parseInt) {
                    if (isFNameSet()) {
                        this.state = PARSE_STATE.FNAME;
                    } else if (isFCommentSet()) {
                        this.state = PARSE_STATE.FCOMMENT;
                    } else if (isFHCRCSet()) {
                        this.state = PARSE_STATE.FHCRC;
                    } else {
                        this.state = PARSE_STATE.DONE;
                    }
                    this.parseOffset = 0;
                }
            } else if (PARSE_STATE.FNAME == this.state) {
                // FNAME is a zero delimited file name
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Parsing FNAME data");
                }
                if (0 != b) {
                    pos = skipPast(data, pos, (byte) 0);
                }
                if (data.length == pos) {
                    return pos;
                }
                if (isFCommentSet()) {
                    this.state = PARSE_STATE.FCOMMENT;
                } else if (isFHCRCSet()) {
                    this.state = PARSE_STATE.FHCRC;
                } else {
                    this.state = PARSE_STATE.DONE;
                }
            } else if (PARSE_STATE.FCOMMENT == this.state) {
                // FCOMMENT is a zero delimited file comment
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Parsing FCOMMENT data");
                }
                if (0 != b) {
                    pos = skipPast(data, pos, (byte) 0);
                }
                if (data.length == pos) {
                    return pos;
                }
                if (isFHCRCSet()) {
                    this.state = PARSE_STATE.FHCRC;
                } else {
                    this.state = PARSE_STATE.DONE;
                }
            } else if (PARSE_STATE.FHCRC == this.state) {
                // FHCRC has 2 extra bytes (checksum of all gzip header bytes)
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Parsing FHCRC data; offset=" + this.parseOffset);
                }
                this.parseOffset++;
                if (2 > this.parseOffset) {
                    continue;
                }
                this.state = PARSE_STATE.DONE;
            }
        } // end loop

        if (PARSE_STATE.DONE == this.state) {
            this.parseOffset = 0;
            this.parseInt = 0;
        }
        return pos;
    }
175803
def multi_encode(self, message, masking_key=None, opcode=None,
                     rsv1=0, rsv2=0, rsv3=0, max_payload=0):
        '''
        '''
        max_payload = max(2, max_payload or self._max_payload)
        opcode, masking_key, data = self._info(message, opcode, masking_key)
        #
        while data:
            if len(data) >= max_payload:
                chunk, data, fin = (data[:max_payload],
                                    data[max_payload:], 0)
            else:
                chunk, data, fin = data, b'', 1
            yield self._encode(chunk, opcode, masking_key, fin,
                               rsv1, rsv2, rsv3)
1064316
def decode_header_part(header):
    
    if not header:
        return six.text_type()

    output = six.text_type()

    try:
        for d, c in decode_header(header):
            c = c if c else 'utf-8'
            output += ported_string(d, c, 'ignore')

    # Header parsing failed, when header has charset Shift_JIS
    except (HeaderParseError, UnicodeError):
        log.error("Failed decoding header part: {}".format(header))
        output += header

    return output
442474
def encode(self):
        
        # Call body before fist_line in case the query is changes.
        first_line = self.first_line()
        if self.body and self.wait_continue:
            self.headers['expect'] = '100-continue'
        headers = self.headers
        if self.unredirected_headers:
            headers = self.unredirected_headers.copy()
            headers.update(self.headers)
        buffer = [first_line.encode('ascii'), b'\r\n']
        buffer.extend((('%s: %s\r\n' % (name, value)).encode(CHARSET)
                      for name, value in headers.items()))
        buffer.append(b'\r\n')
        return b''.join(buffer)
789138
def decode_body(buffer, header=nil)
      return [nil, buffer] if buffer.size < Frame.header_size

      header ||= decode_header buffer[0, Frame.header_size + Frame.mac_size]
      body_size = Frame.decode_body_size header

      if @frame_cipher
        body = @frame_cipher.decrypt_body(buffer[(Frame.header_size+Frame.mac_size)..-1], body_size)
        raise MultiplexerError, 'body length mismatch' unless body.size == body_size

        bytes_read = Frame.header_size + Frame.mac_size + Utils.ceil16(body.size) + Frame.mac_size
      else
        header = buffer[0, Frame.header_size]
        body_offset = Frame.header_size + Frame.mac_size
        body = buffer[body_offset, body_size]
        raise MultiplexerError, 'body length mismatch' unless body.size == body_size

        bytes_read = Utils.ceil16(body_offset + body_size + Frame.mac_size)
      end
      raise MultiplexerError, "bytes not padded" unless bytes_read % Frame.padding == 0

      # normal, chunked-n: RLP::List.new(protocol_type[, sequence_id])
      # chunked-0: RLP::List.new(protocol_type, sequence_id, total_packet_size)
      header_data = nil
      begin
        header_data = RLP.decode(header[3..-1], sedes: Frame.header_sedes, strict: false)
      rescue RLP::Error::RLPException => e
        logger.error(e)
        raise MultiplexerError, 'invalid rlp data'
      end

      if header_data.size == 3
        chunked_0 = true
        total_payload_size = header_data[2]
        raise MultiplexerError, "invalid total payload size" unless total_payload_size < 2**32
      else
        chunked_0 = false
        total_payload_size = nil
      end

      protocol_id = header_data[0]
      raise MultiplexerError, "invalid protocol id" unless protocol_id < TT16

      if header_data.size > 1
        sequence_id = header_data[1]
        raise MultiplexerError, "invalid sequence id" unless sequence_id < TT16
      else
        sequence_id = nil
      end

      raise MultiplexerError, "unknown protocol id #{protocol_id}" unless @chunked_buffers.has_key?(protocol_id)

      chunkbuf = @chunked_buffers[protocol_id]
      if chunkbuf.has_key?(sequence_id)
        packet = chunkbuf[sequence_id]

        raise MultiplexerError, "received chunked_0 frame for existing buffer #{sequence_id} of protocol #{protocol_id}" if chunked_0
        raise MultiplexerError, "too much data for chunked buffer #{sequence_id} of protocol #{protocol_id}" if body.size > (packet.total_payload_size - packet.payload.size)

        packet.payload += body
        if packet.total_payload_size == packet.payload.size
          packet.total_payload_size = nil
          chunkbuf.delete sequence_id
          return packet
        end
      else
        # body of normal, chunked_0: rlp(packet-type) [|| rlp(packet-data)] || padding
        item, item_end = RLP.consume_item(body, 0)
        cmd_id = RLP::Sedes.big_endian_int.deserialize item

        if chunked_0
          payload = body[item_end..-1]
          total_payload_size -= item_end
        else
          payload = body[item_end..-1]
        end

        packet = Packet.new protocol_id, cmd_id, payload
        if chunked_0
          raise MultiplexerError, "total payload size smaller than initial chunk" if total_payload_size < payload.size

          # shouldn't have been chunked, whatever
          return packet if total_payload_size == payload.size

          raise MultiplexerError, 'chunked_0 must have sequence id' if sequence_id.nil?

          packet.total_payload_size = total_payload_size
          chunkbuf[sequence_id] = packet

          return nil
        else
          return packet # normal (non-chunked)
        end
      end
    end
88576
function deflate_internal(buff, off, buff_size) {
		var n;

		if (!initflag) {
			init_deflate();
			initflag = true;
			if (lookahead === 0) { // empty
				complete = true;
				return 0;
			}
		}

		n = qcopy(buff, off, buff_size);
		if (n === buff_size) {
			return buff_size;
		}

		if (complete) {
			return n;
		}

		if (compr_level <= 3) {
			// optimized for speed
			deflate_fast();
		} else {
			deflate_better();
		}

		if (lookahead === 0) {
			if (match_available) {
				ct_tally(0, window[strstart - 1] & 0xff);
			}
			flush_block(1);
			complete = true;
		}

		return n + qcopy(buff, n + off, buff_size - n);
	}
595197
def _encode(msg, head=False, binary=False):
    
    rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
        msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)

    if not head and msg.data:
        if not binary and isinstance(msg.data, six.string_types):
            return (rawstr + ' ' +
                    'text/ascii' + ' ' + msg.data)
        elif not binary:
            return (rawstr + ' ' +
                    'application/json' + ' ' +
                    json.dumps(msg.data, default=datetime_encoder))
        else:
            return (rawstr + ' ' +
                    'binary/octet-stream' + ' ' + msg.data)
    return rawstr
1173019
function parse(header) {
  var mustUnescape = false;
  var isEscaping = false;
  var inQuotes = false;
  var forwarded = {};
  var output = [];
  var start = -1;
  var end = -1;
  var parameter;
  var code;

  for (var i = 0; i < header.length; i++) {
    code = header.charCodeAt(i);

    if (parameter === undefined) {
      if (start === -1 && (code === 0x20/*' '*/|| code === 0x09/*'\t'*/)) {
        continue;
      }

      if (isTokenChar(code)) {
        if (start === -1) start = i;
      } else if (code === 0x3D/*'='*/ && start !== -1) {
        parameter = header.slice(start, i).toLowerCase();
        start = -1;
      } else {
        throw new ParseError(unexpectedCharacterMessage(header, i), header);
      }
    } else {
      if (isEscaping && (code === 0x09 || isPrint(code) || isExtended(code))) {
        isEscaping = false;
      } else if (isTokenChar(code)) {
        if (end !== -1) {
          throw new ParseError(unexpectedCharacterMessage(header, i), header);
        }

        if (start === -1) start = i;
      } else if (isDelimiter(code) || isExtended(code)) {
        if (inQuotes) {
          if (code === 0x22/*'"'*/) {
            inQuotes = false;
            end = i;
          } else if (code === 0x5C/*'\'*/) {
            if (start === -1) start = i;
            isEscaping = mustUnescape = true;
          } else if (start === -1) {
            start = i;
          }
        } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3D) {
          inQuotes = true;
        } else if (
          (code === 0x2C/*','*/|| code === 0x3B/*';'*/) &&
          (start !== -1 || end !== -1)
        ) {
          if (start !== -1) {
            if (end === -1) end = i;
            forwarded[parameter] = mustUnescape
              ? decode(header.slice(start, end))
              : header.slice(start, end);
          } else {
            forwarded[parameter] = '';
          }

          if (code === 0x2C) {
            output.push(forwarded);
            forwarded = {};
          }

          parameter = undefined;
          start = end = -1;
        } else {
          throw new ParseError(unexpectedCharacterMessage(header, i), header);
        }
      } else if (code === 0x20 || code === 0x09) {
        if (end !== -1) continue;

        if (inQuotes) {
          if (start === -1) start = i;
        } else if (start !== -1) {
          end = i;
        } else {
          throw new ParseError(unexpectedCharacterMessage(header, i), header);
        }
      } else {
        throw new ParseError(unexpectedCharacterMessage(header, i), header);
      }
    }
  }

  if (parameter === undefined || inQuotes || start === -1 && end === -1) {
    throw new ParseError('Unexpected end of input', header);
  }

  if (start !== -1) {
    if (end === -1) end = i;
    forwarded[parameter] = mustUnescape
      ? decode(header.slice(start, end))
      : header.slice(start, end);
  } else {
    forwarded[parameter] = '';
  }

  output.push(forwarded);
  return output;
}
890385
def decode_response(response):
    
    def is_compressed(headers):
        encoding = headers.get('content-encoding', [])
        return encoding and encoding[0] in ('gzip', 'deflate')

    def decompress_body(body, encoding):
        """Returns decompressed body according to encoding using zlib.
        to (de-)compress gzip format, use wbits = zlib.MAX_WBITS | 16
        """
        if encoding == 'gzip':
            return zlib.decompress(body, zlib.MAX_WBITS | 16)
        else:  # encoding == 'deflate'
            return zlib.decompress(body)

    # Deepcopy here in case `headers` contain objects that could
    # be mutated by a shallow copy and corrupt the real response.
    response = copy.deepcopy(response)
    headers = CaseInsensitiveDict(response['headers'])
    if is_compressed(headers):
        encoding = headers['content-encoding'][0]
        headers['content-encoding'].remove(encoding)
        if not headers['content-encoding']:
            del headers['content-encoding']

        new_body = decompress_body(response['body']['string'], encoding)
        response['body']['string'] = new_body
        headers['content-length'] = [str(len(new_body))]
        response['headers'] = dict(headers)
    return response
1185407
function(buff, offset, n) {
    var i;
    for(i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++)
	buff[offset + i] =
	    zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff;
    return i;
}
9931
def decode_headers(header_list):
	'''
	
	'''

	decoded_headers = []
	for header in header_list:
		if cchardet:
			inferred = cchardet.detect(header)
			if inferred and inferred['confidence'] > 0.8:
				# print("Parsing headers!", header)
				decoded_headers.append(header.decode(inferred['encoding']))
			else:
				decoded_headers.append(header.decode('iso-8859-1'))
		else:    # pragma: no cover
			# All bytes are < 127 (e.g. ASCII)
			if all([char & 0x80 == 0 for char in header]):
				decoded_headers.append(header.decode("us-ascii"))
			elif isUTF8Strict(header):
				decoded_headers.append(header.decode("utf-8"))
			else:
				decoded_headers.append(header.decode('iso-8859-1'))

	return decoded_headers
594415
def percent_encode_non_ascii_headers(self, encoding='UTF-8'):
        
        def do_encode(m):
            return "*={0}''".format(encoding) + quote(to_native_str(m.group(1)))

        for index in range(len(self.headers) - 1, -1, -1):
            curr_name, curr_value = self.headers[index]
            try:
                # test if header is ascii encodable, no action needed
                curr_value.encode('ascii')
            except:
                new_value = self.ENCODE_HEADER_RX.sub(do_encode, curr_value)
                if new_value == curr_value:
                    new_value = quote(curr_value)

                self.headers[index] = (curr_name, new_value)
73702
function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
		{
			// check if $_SERVER is populated: it might have been disabled via ini file
			// (this is true even when in CLI mode)
			if (count($_SERVER) == 0)
			{
				error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');
			}

			if($this->debug > 1)
			{
				if(function_exists('getallheaders'))
				{
					$this->debugmsg(''); // empty line
					foreach(getallheaders() as $name => $val)
					{
						$this->debugmsg("HEADER: $name: $val");
					}
				}

			}

			if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
			{
				$content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
			}
			else
			{
				$content_encoding = '';
			}

			// check if request body has been compressed and decompress it
			if($content_encoding != '' && strlen($data))
			{
				if($content_encoding == 'deflate' || $content_encoding == 'gzip')
				{
					// if decoding works, use it. else assume data wasn't gzencoded
					if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
					{
						if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
						{
							$data = $degzdata;
							if($this->debug > 1)
							{
								$this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
							}
						}
						elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
						{
							$data = $degzdata;
							if($this->debug > 1)
								$this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
						}
						else
						{
							$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']);
							return $r;
						}
					}
					else
					{
						//error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
						$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']);
						return $r;
					}
				}
			}

			// check if client specified accepted charsets, and if we know how to fulfill
			// the request
			if ($this->response_charset_encoding == 'auto')
			{
				$resp_encoding = '';
				if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
				{
					// here we should check if we can match the client-requested encoding
					// with the encodings we know we can generate.
					/// @todo we should parse q=0.x preferences instead of getting first charset specified...
					$client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
					// Give preference to internal encoding
					$known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII');
					foreach ($known_charsets as $charset)
					{
						foreach ($client_accepted_charsets as $accepted)
							if (strpos($accepted, $charset) === 0)
							{
								$resp_encoding = $charset;
								break;
							}
						if ($resp_encoding)
							break;
					}
				}
			}
			else
			{
				$resp_encoding = $this->response_charset_encoding;
			}

			if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
			{
				$resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
			}
			else
			{
				$resp_compression = '';
			}

			// 'guestimate' request encoding
			/// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
			$req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
				$data);

			return null;
		}
172426
def _pkcs1imify(self, data):
        
        size = len(util.deflate_long(self.n, 0))
        filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) - 3)
        return zero_byte + one_byte + filler + zero_byte + SHA1_DIGESTINFO + data
484961
function read_buff(buff, offset, n) {
		var i;
		for (i = 0; i < n && deflate_pos < deflate_data.length; i++) {
			buff[offset + i] = deflate_data[deflate_pos++] & 0xff;
		}
		return i;
	}
1195577
def deflate_long(n, add_sign_padding=True):
    """"""
    # after much testing, this algorithm was deemed to be the fastest
    s = bytes()
    n = long(n)
    while (n != 0) and (n != -1):
        s = struct.pack('>I', n & xffffffff) + s
        n >>= 32
    # strip off leading zeros, FFs
    for i in enumerate(s):
        if (n == 0) and (i[1] != deflate_zero):
            break
        if (n == -1) and (i[1] != deflate_ff):
            break
    else:
        # degenerate case, n was either 0 or -1
        i = (0,)
        if n == 0:
            s = zero_byte
        else:
            s = max_byte
    s = s[i[0]:]
    if add_sign_padding:
        if (n == 0) and (byte_ord(s[0]) >= 0x80):
            s = zero_byte + s
        if (n == -1) and (byte_ord(s[0]) < 0x80):
            s = max_byte + s
    return s