Parses headers from a string.
352236
public static function parse(string $data): self
    {
        if (preg_match_all('/([^:\r\n]+):\s+([^\r\n]*(\r\n[ \t][^\r\n]+)*)\r\n/', $data, $matches, PREG_SET_ORDER) === false) {
            throw new FormatException('Invalid header format');
        }

        foreach ($matches as $match) {
            // Undo header folding.
            $value = preg_replace('/\r\n[ \t]([^\r\n]+)/', ' $1', $match[2]);

            $headers[$match[1]] = $value;
        }

        return new self($headers);
    }
157026
public static function parseHeaders(string $headers): array
    {
        $res = [];

        foreach (explode("\r\n", $headers) as $line) {
            $line = trim($line);
            if (!$line) {
                continue;
            }

            $line = explode(': ', $line);
            if (count($line) !== 2) {
                continue;
            }

            $res[strtolower($line[0])] = $line[1];
        }

        return $res;
    }
603835
def _parse_header(lines):
    
    header_count = _extract_header_number(lines)
    header_dict = {}
    for i in range(2, header_count + 2):
        pair = _extract_header_value(lines[i])

        if not pair:  # Ignore empty strings
            continue

        header_dict.update(pair)
    return header_dict
219299
def parseAcceptHeader(value):
    
    chunks = [chunk.strip() for chunk in value.split(',')]
    accept = []
    for chunk in chunks:
        parts = [s.strip() for s in chunk.split(';')]

        mtype = parts.pop(0)
        if '/' not in mtype:
            # This is not a MIME type, so ignore the bad data
            continue

        main, sub = mtype.split('/', 1)

        for ext in parts:
            if '=' in ext:
                k, v = ext.split('=', 1)
                if k == 'q':
                    try:
                        q = float(v)
                        break
                    except ValueError:
                        # Ignore poorly formed q-values
                        pass
        else:
            q = 1.0

        accept.append((q, main, sub))

    accept.sort()
    accept.reverse()
    return [(main, sub, q) for (q, main, sub) in accept]
575461
public static String parseCharset(Map<String, String> headers) {
        return parseCharset(headers, HTTP.DEFAULT_CONTENT_CHARSET);
    }
1320725
public static function parse_headers(string $headers): array
    {
        $final_headers = array();
        $list = explode("\n", trim($headers));

        $http = array_shift($list);

        foreach ($list as $header) {
            $parts = explode(':', $header, 2);
            $final_headers[trim($parts[0])] = isset($parts[1]) ? trim($parts[1]) : '';
        }

        return $final_headers;
    }
495020
function (headers) {
      var parsed = {};

      if (headers) {
        headers = headers.trim().split("\n");
        for (var h in headers) {
          if (headers.hasOwnProperty(h)) {
            var header = headers[h].match(/([^:]+):(.*)/);
            parsed[header[1].trim().toLowerCase()] = header[2].trim();
          }
        }
      }
      return parsed;
    }
1243754
def parse_charset(header_string):
    '''
    '''
    match = re.search(
        r'''charset[ ]?=[ ]?["']?([a-z0-9_-]+)''',
        header_string,
        re.IGNORECASE
    )

    if match:
        return match.group(1)
1178846
private function parseHeader($header) {
        if(!empty($header)) {
            $pos = strpos($header, ": ");

            if(false !== $pos) {
                $name = substr($header,0,$pos);
                $value = substr($header,$pos+2);

                $this->headers[$name] = $value;
            }
        }
    }
160835
function parseHeaders(headers) {
    var out = {};
    var position = 0;
    while (position < headers.length) {
        var nameLength = headers.readUInt8(position++);
        var name = headers.slice(position, position + nameLength).toString();
        position += nameLength;
        switch (headers.readUInt8(position++)) {
            case 0 /* boolTrue */:
                out[name] = {
                    type: BOOLEAN_TAG,
                    value: true
                };
                break;
            case 1 /* boolFalse */:
                out[name] = {
                    type: BOOLEAN_TAG,
                    value: false
                };
                break;
            case 2 /* byte */:
                out[name] = {
                    type: BYTE_TAG,
                    value: headers.readInt8(position++)
                };
                break;
            case 3 /* short */:
                out[name] = {
                    type: SHORT_TAG,
                    value: headers.readInt16BE(position)
                };
                position += 2;
                break;
            case 4 /* integer */:
                out[name] = {
                    type: INT_TAG,
                    value: headers.readInt32BE(position)
                };
                position += 4;
                break;
            case 5 /* long */:
                out[name] = {
                    type: LONG_TAG,
                    value: new Int64(headers.slice(position, position + 8))
                };
                position += 8;
                break;
            case 6 /* byteArray */:
                var binaryLength = headers.readUInt16BE(position);
                position += 2;
                out[name] = {
                    type: BINARY_TAG,
                    value: headers.slice(position, position + binaryLength)
                };
                position += binaryLength;
                break;
            case 7 /* string */:
                var stringLength = headers.readUInt16BE(position);
                position += 2;
                out[name] = {
                    type: STRING_TAG,
                    value: headers.slice(
                        position,
                        position + stringLength
                    ).toString()
                };
                position += stringLength;
                break;
            case 8 /* timestamp */:
                out[name] = {
                    type: TIMESTAMP_TAG,
                    value: new Date(
                        new Int64(headers.slice(position, position + 8))
                            .valueOf()
                    )
                };
                position += 8;
                break;
            case 9 /* uuid */:
                var uuidChars = headers.slice(position, position + 16)
                    .toString('hex');
                position += 16;
                out[name] = {
                    type: UUID_TAG,
                    value: uuidChars.substr(0, 8) + '-' +
                        uuidChars.substr(8, 4) + '-' +
                        uuidChars.substr(12, 4) + '-' +
                        uuidChars.substr(16, 4) + '-' +
                        uuidChars.substr(20)
                };
                break;
            default:
                throw new Error('Unrecognized header type tag');
        }
    }
    return out;
}
166653
function parseHeaders(headers) {
  var parsed = {}, key, val, i;

  if (!headers) return parsed;

  forEach(headers.split('\n'), function(line) {
    i = line.indexOf(':');
    key = lowercase(trim(line.substr(0, i)));
    val = trim(line.substr(i + 1));

    if (key) {
      if (parsed[key]) {
        parsed[key] += ', ' + val;
      } else {
        parsed[key] = val;
      }
    }
  });

  return parsed;
}
394352
def parse_header(filename):
    '''
    '''
    with open(filename, 'rb') as fh:
        content = '\n'.join(fh.read().splitlines())

    content = sub('\t', ' ', content)
    content = strip_comments(content)

    # first get the functions
    content = split(func_pat_short, content)

    for i, s in enumerate(content):
        if i % 2 and content[i].strip():  # matched a prototype
            try:
                content[i] = parse_prototype(content[i])
            except Exception as e:
                traceback.print_exc()

    # now process structs
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already a func etc. skip it
            res.append(item)
            continue

        items = split(struct_pat, item)
        j = 0
        while j < len(items):
            if not j % 5:
                res.append(items[j])
                j += 1
            else:
                if items[j].strip() == 'enum':
                    res.append(parse_enum(*items[j + 1: j + 4]))
                else:
                    res.append(parse_struct(*items[j + 1: j + 4]))
                j += 4

    # now do remaining simple typedefs
    content = res
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already processed skip it
            res.append(item)
            continue

        items = split(typedef_pat, item)
        for j, item in enumerate(items):
            res.append(TypeDef(item.strip()) if j % 2 else item)

    content = [c for c in res if not isinstance(c, str) or c.strip()]
    return content
753917
protected final boolean parseHeaders(ByteBuffer in) throws BaseExceptions.BadMessage, BaseExceptions.InvalidState {

        headerLoop: while (true) {
            char ch;
            switch (_hstate) {
                case START:
                    _hstate = HeaderState.HEADER_IN_NAME;
                    resetLimit(headerSizeLimit);

                case HEADER_IN_NAME:
                    for(ch = next(in, false); ch != ':' && ch != HttpTokens.LF; ch = next(in, false)) {
                        if (ch == HttpTokens.EMPTY_BUFF) return false;
                        putChar(ch);
                    }

                    // Must be done with headers
                    if (bufferPosition() == 0) {
                        _hstate = HeaderState.END;

                        // Finished with the whole request
                        if (_chunkState == ChunkState.CHUNK_TRAILERS) {
                            shutdownParser();
                        }
                        else if ((_endOfContent == EndOfContent.UNKNOWN_CONTENT && mustNotHaveBody())) {
                            shutdownParser();
                        }

                        // Done parsing headers
                        return true;
                    }

                    if (ch == HttpTokens.LF) {  // Valueless header
                        String name = getString();
                        clearBuffer();

                        if (headerComplete(name, "")) {
                            return true;
                        }

                        continue headerLoop;    // Still parsing Header name
                    }

                    _headerName = getString();
                    clearBuffer();
                    _hstate = HeaderState.HEADER_IN_VALUE;

                case HEADER_IN_VALUE:
                    for(ch = next(in, true); ch != HttpTokens.LF; ch = next(in, true)) {
                        if (ch == HttpTokens.EMPTY_BUFF) return false;
                        putChar(ch);
                    }

                    String value;
                    try { value = getTrimmedString(); }
                    catch (BaseExceptions.BadMessage e) {
                        shutdownParser();
                        throw e;
                    }
                    clearBuffer();

                    // If we are not parsing trailer headers, look for some that are of interest to the request
                    if (_chunkState != ChunkState.CHUNK_TRAILERS) {
                        if (_headerName.equalsIgnoreCase("Transfer-Encoding")) {
                            if (value.equalsIgnoreCase("chunked")) {
                                // chunked always overrides Content-Length
                                if (_endOfContent != EndOfContent.END) {
                                    _endOfContent = EndOfContent.CHUNKED_CONTENT;
                                }
                            } else if (value.equalsIgnoreCase("identity")) {
                                // TODO: remove support for identity Transfer-Encoding.
                                // It  was removed from the specification before it was published 
                                // (althoug some traces of it remained until errata was released: 
                                // http://lists.w3.org/Archives/Public/ietf-http-wg-old/2001SepDec/0018.html
                                // if (_endOfContent == EndOfContent.UNKNOWN_CONTENT) {
                                //     _endOfContent = EndOfContent.EOF_CONTENT; 
                                // }
                            }
                            else {
                                shutdownParser();
                                // TODO: server should return 501 - https://tools.ietf.org/html/rfc7230#page-30
                                throw new BadMessage("Unknown Transfer-Encoding: " + value);
                            }
                        }
                        else if (_endOfContent != EndOfContent.CHUNKED_CONTENT && _headerName.equalsIgnoreCase("Content-Length")) {
                            try {
                                long len = Long.parseLong(value);
                                if ((_endOfContent == EndOfContent.NO_CONTENT || 
                                     _endOfContent == EndOfContent.CONTENT_LENGTH) && len != _contentLength) {
                                    // Multiple different Content-Length headers are an error
                                    // https://tools.ietf.org/html/rfc7230#page-31
                                    long oldLen = _contentLength;
                                    shutdownParser();
                                    throw new BadMessage("Duplicate Content-Length headers detected: " +
                                                         oldLen + " and " + len + "\n");
                                }
                                else if (len > 0) {
                                    _contentLength = len;
                                    _endOfContent = EndOfContent.CONTENT_LENGTH;
                                }
                                else if (len == 0) {
                                    _contentLength = len;
                                    _endOfContent = EndOfContent.NO_CONTENT;
                                }
                                else { // negative content-length
                                    shutdownParser();
                                    throw new BadMessage("Cannot have negative Content-Length: '" + len + "'\n");
                                }
                            }
                            catch (NumberFormatException t) {
                                shutdownParser();
                                throw new BadMessage("Invalid Content-Length: '" + value + "'\n");
                            }
                        }
                    }

                    // Send off the header and see if we wish to continue
                    try {
                        if (headerComplete(_headerName, value)) {
                            return true;
                        }
                    } finally {
                        _hstate = HeaderState.HEADER_IN_NAME;
                    }

                    break;

                case END:
                    shutdownParser();
                    throw new InvalidState("Header parser reached invalid position.");
            }   // Switch
        }   // while loop
    }
147928
static void parseHeader(final String header, Map<Token, String> response) {
        if (response.size() == Token.values().length) {
            //already parsed everything
            return;
        }
        char[] headerChars = header.toCharArray();

        SearchingFor searchingFor = SearchingFor.START_OF_NAME;
        int nameStart = 0;
        Token currentToken = null;
        int valueStart = 0;

        int escapeCount = 0;
        boolean containsEscapes = false;

        for (int i = 0; i < headerChars.length; i++) {
            switch (searchingFor) {
                case START_OF_NAME:
                    // Eliminate any white space before the name of the parameter.
                    if (headerChars[i] != ';' && !Character.isWhitespace(headerChars[i])) {
                        nameStart = i;
                        searchingFor = SearchingFor.EQUALS_SIGN;
                    }
                    break;
                case EQUALS_SIGN:
                    if (headerChars[i] == '=') {
                        String paramName = String.valueOf(headerChars, nameStart, i - nameStart);
                        currentToken = TOKENS.get(paramName.toLowerCase(Locale.ENGLISH));
                        //we allow unkown tokens, but just ignore them
                        searchingFor = SearchingFor.START_OF_VALUE;
                    }
                    break;
                case START_OF_VALUE:
                    if (!Character.isWhitespace(headerChars[i])) {
                        if (headerChars[i] == '"') {
                            valueStart = i + 1;
                            searchingFor = SearchingFor.LAST_QUOTE;
                        } else {
                            valueStart = i;
                            searchingFor = SearchingFor.END_OF_VALUE;
                        }
                    }
                    break;
                case LAST_QUOTE:
                    if (headerChars[i] == '\\') {
                        escapeCount++;
                        containsEscapes = true;
                    } else if (headerChars[i] == '"' && (escapeCount % 2 == 0)) {
                        String value = String.valueOf(headerChars, valueStart, i - valueStart);
                        if (containsEscapes) {
                            StringBuilder sb = new StringBuilder();
                            boolean lastEscape = false;
                            for (int j = 0; j < value.length(); ++j) {
                                char c = value.charAt(j);
                                if (c == '\\' && !lastEscape) {
                                    lastEscape = true;
                                } else {
                                    lastEscape = false;
                                    sb.append(c);
                                }
                            }
                            value = sb.toString();
                            containsEscapes = false;
                        }
                        if (currentToken != null && !response.containsKey(currentToken)) {
                            response.put(currentToken, value);
                        }

                        searchingFor = SearchingFor.START_OF_NAME;
                        escapeCount = 0;
                    } else {
                        escapeCount = 0;
                    }
                    break;
                case END_OF_VALUE:
                    if (headerChars[i] == ';' || headerChars[i] == ',' || Character.isWhitespace(headerChars[i])) {
                        String value = String.valueOf(headerChars, valueStart, i - valueStart);
                        if (currentToken != null && !response.containsKey(currentToken)) {
                            response.put(currentToken, value);
                        }

                        searchingFor = SearchingFor.START_OF_NAME;
                    }
                    break;
            }
        }

        if (searchingFor == SearchingFor.END_OF_VALUE) {
            // Special case where we reached the end of the array containing the header values.
            String value = String.valueOf(headerChars, valueStart, headerChars.length - valueStart);
            if (currentToken != null && !response.containsKey(currentToken)) {
                response.put(currentToken, value);
            }
        } else if (searchingFor != SearchingFor.START_OF_NAME) {
            // Somehow we are still in the middle of searching for a current value.
            throw MESSAGES.invalidHeader();
        }

    }
597773
public static function parse($headers)
    {
        if (is_string($headers)) {
            $headers = explode("\r\n\r\n", trim($headers));

            return explode("\r\n", end($headers));
        }

        $parsedHeaders = [];

        foreach ($headers as $name => $value) {
            $value = HeadersNormalizer::normalizeHeaderValue($value);

            if (is_int($name)) {
                if (strpos($value, 'HTTP/') === 0) {
                    $parsedHeaders = [$value];
                } else {
                    $parsedHeaders[] = $value;
                }
            } else {
                $parsedHeaders[] = $name.': '.$value;
            }
        }

        return $parsedHeaders;
    }
1339935
private String[] extractAndDecodeHeader(String header) throws IOException {

        byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET);
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, CREDENTIALS_CHARSET);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[] {token.substring(0, delim), token.substring(delim + 1)};
    }
185668
def parse_headers_link(headers):
    """"""

    header = CaseInsensitiveDict(headers).get('link')

    l = {}

    if header:
        links = parse_link(header)

        for link in links:
            key = link.get('rel') or link.get('url')
            l[key] = link

    return l