Parse a header frame for a channel given a Reader payload.
341164
def parse(self, channel_id, payload):
        '''
        
        '''
        class_id = payload.read_short()
        weight = payload.read_short()
        size = payload.read_longlong()
        properties = {}

        # The AMQP spec is overly-complex when it comes to handling header
        # frames. The spec says that in addition to the first 16bit field,
        # additional ones can follow which /may/ then be in the property list
        # (because bit flags aren't in the list). Properly implementing custom
        # values requires the ability change the properties and their types,
        # which someone is welcome to do, but seriously, what's the point?
        # Because the complexity of parsing and writing this frame directly
        # impacts the speed at which messages can be processed, there are two
        # branches for both a fast parse which assumes no changes to the
        # properties and a slow parse. For now it's up to someone using custom
        # headers to flip the flag.
        if self.DEFAULT_PROPERTIES:
            flag_bits = payload.read_short()
            for key, proptype, rfunc, wfunc, mask in self.PROPERTIES:
                if flag_bits & mask:
                    properties[key] = rfunc(payload)
        else:
            flags = []
            while True:
                flag_bits = payload.read_short()
                flags.append(flag_bits)
                if flag_bits & 1 == 0:
                    break

            shift = 0
            for key, proptype, rfunc, wfunc, mask in self.PROPERTIES:
                if shift == 0:
                    if not flags:
                        break
                    flag_bits, flags = flags[0], flags[1:]
                    shift = 15
                if flag_bits & (1 << shift):
                    properties[key] = rfunc(payload)
                shift -= 1

        return HeaderFrame(channel_id, class_id, weight, size, properties)
1169349
def frame_from_raw(raw):
    """"""
    command, payload = extract_from_frame(raw)
    frame = create_frame(command)
    if frame is None:
        PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
        return None
    frame.validate_payload_len(payload)
    frame.from_payload(payload)
    return frame
1322090
private void readHeader() throws IOException {
    headerBuffer.rewind();

    final int flgRead = in.read();
    if (flgRead < 0) {
      throw new IOException(PREMATURE_EOS);
    }
    final int bdRead = in.read();
    if (bdRead < 0) {
      throw new IOException(PREMATURE_EOS);
    }

    final byte flgByte = (byte)(flgRead & 0xFF);
    final LZ4FrameOutputStream.FLG flg = LZ4FrameOutputStream.FLG.fromByte(flgByte);
    headerBuffer.put(flgByte);
    final byte bdByte = (byte)(bdRead & 0xFF);
    final LZ4FrameOutputStream.BD bd = LZ4FrameOutputStream.BD.fromByte(bdByte);
    headerBuffer.put(bdByte);

    this.frameInfo = new LZ4FrameOutputStream.FrameInfo(flg, bd);

    if (flg.isEnabled(LZ4FrameOutputStream.FLG.Bits.CONTENT_SIZE)) {
      expectedContentSize = readLong(in);
      headerBuffer.putLong(expectedContentSize);
    }
    totalContentSize = 0L;

    // check stream descriptor hash
    final byte hash = (byte) ((checksum.hash(headerArray, 0, headerBuffer.position(), 0) >> 8) & 0xFF);
    final int expectedHash = in.read();
    if (expectedHash < 0) {
      throw new IOException(PREMATURE_EOS);
    }

    if (hash != (byte)(expectedHash & 0xFF)) {
      throw new IOException(DESCRIPTOR_HASH_MISMATCH);
    }

    maxBlockSize = frameInfo.getBD().getBlockMaximumSize();
    compressedBuffer = new byte[maxBlockSize]; // Reused during different compressions
    rawBuffer = new byte[maxBlockSize];
    buffer = ByteBuffer.wrap(rawBuffer);
    buffer.limit(0);
  }
169755
def parse_packets(stream):
    
    reader = util.Reader(stream)
    while True:
        try:
            value = reader.readfmt('B')
        except EOFError:
            return

        log.debug('prefix byte: %s', bin(value))
        assert util.bit(value, 7) == 1

        tag = util.low_bits(value, 6)
        if util.bit(value, 6) == 0:
            length_type = util.low_bits(tag, 2)
            tag = tag >> 2
            fmt = {0: '>B', 1: '>H', 2: '>L'}[length_type]
            packet_size = reader.readfmt(fmt)
        else:
            first = reader.readfmt('B')
            if first < 192:
                packet_size = first
            elif first < 224:
                packet_size = ((first - 192) << 8) + reader.readfmt('B') + 192
            elif first == 255:
                packet_size = reader.readfmt('>L')
            else:
                log.error('Partial Body Lengths unsupported')

        log.debug('packet length: %d', packet_size)
        packet_data = reader.read(packet_size)
        packet_type = PACKET_TYPES.get(tag)

        p = {'type': 'unknown', 'tag': tag, 'raw': packet_data}
        if packet_type is not None:
            try:
                p = packet_type(util.Reader(io.BytesIO(packet_data)))
                p['tag'] = tag
            except ValueError:
                log.exception('Skipping packet: %s', util.hexlify(packet_data))

        log.debug('packet "%s": %s', p['type'], p)
        yield p
914180
def Deserialize(self, reader):
        
        super(Header, self).Deserialize(reader)
        if reader.ReadByte() != 0:
            raise Exception('Incorrect Header Format')
180551
def parse_frame(self, buf: bytes) -> List[Tuple[bool, Optional[int],
                                                    bytearray,
                                                    Optional[bool]]]:
        """"""
        frames = []
        if self._tail:
            buf, self._tail = self._tail + buf, b''

        start_pos = 0
        buf_length = len(buf)

        while True:
            # read header
            if self._state == WSParserState.READ_HEADER:
                if buf_length - start_pos >= 2:
                    data = buf[start_pos:start_pos+2]
                    start_pos += 2
                    first_byte, second_byte = data

                    fin = (first_byte >> 7) & 1
                    rsv1 = (first_byte >> 6) & 1
                    rsv2 = (first_byte >> 5) & 1
                    rsv3 = (first_byte >> 4) & 1
                    opcode = first_byte & 0xf

                    # frame-fin = %x0 ; more frames of this message follow
                    #           / %x1 ; final frame of this message
                    # frame-rsv1 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    # frame-rsv2 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    # frame-rsv3 = %x0 ;
                    #    1 bit, MUST be 0 unless negotiated otherwise
                    #
                    # Remove rsv1 from this test for deflate development
                    if rsv2 or rsv3 or (rsv1 and not self._compress):
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received frame with non-zero reserved bits')

                    if opcode > 0x7 and fin == 0:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received fragmented control frame')

                    has_mask = (second_byte >> 7) & 1
                    length = second_byte & 0x7f

                    # Control frames MUST have a payload
                    # length of 125 bytes or less
                    if opcode > 0x7 and length > 125:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Control frame payload cannot be '
                            'larger than 125 bytes')

                    # Set compress status if last package is FIN
                    # OR set compress status if this is first fragment
                    # Raise error if not first fragment with rsv1 = 0x1
                    if self._frame_fin or self._compressed is None:
                        self._compressed = True if rsv1 else False
                    elif rsv1:
                        raise WebSocketError(
                            WSCloseCode.PROTOCOL_ERROR,
                            'Received frame with non-zero reserved bits')

                    self._frame_fin = bool(fin)
                    self._frame_opcode = opcode
                    self._has_mask = bool(has_mask)
                    self._payload_length_flag = length
                    self._state = WSParserState.READ_PAYLOAD_LENGTH
                else:
                    break

            # read payload length
            if self._state == WSParserState.READ_PAYLOAD_LENGTH:
                length = self._payload_length_flag
                if length == 126:
                    if buf_length - start_pos >= 2:
                        data = buf[start_pos:start_pos+2]
                        start_pos += 2
                        length = UNPACK_LEN2(data)[0]
                        self._payload_length = length
                        self._state = (
                            WSParserState.READ_PAYLOAD_MASK
                            if self._has_mask
                            else WSParserState.READ_PAYLOAD)
                    else:
                        break
                elif length > 126:
                    if buf_length - start_pos >= 8:
                        data = buf[start_pos:start_pos+8]
                        start_pos += 8
                        length = UNPACK_LEN3(data)[0]
                        self._payload_length = length
                        self._state = (
                            WSParserState.READ_PAYLOAD_MASK
                            if self._has_mask
                            else WSParserState.READ_PAYLOAD)
                    else:
                        break
                else:
                    self._payload_length = length
                    self._state = (
                        WSParserState.READ_PAYLOAD_MASK
                        if self._has_mask
                        else WSParserState.READ_PAYLOAD)

            # read payload mask
            if self._state == WSParserState.READ_PAYLOAD_MASK:
                if buf_length - start_pos >= 4:
                    self._frame_mask = buf[start_pos:start_pos+4]
                    start_pos += 4
                    self._state = WSParserState.READ_PAYLOAD
                else:
                    break

            if self._state == WSParserState.READ_PAYLOAD:
                length = self._payload_length
                payload = self._frame_payload

                chunk_len = buf_length - start_pos
                if length >= chunk_len:
                    self._payload_length = length - chunk_len
                    payload.extend(buf[start_pos:])
                    start_pos = buf_length
                else:
                    self._payload_length = 0
                    payload.extend(buf[start_pos:start_pos+length])
                    start_pos = start_pos + length

                if self._payload_length == 0:
                    if self._has_mask:
                        assert self._frame_mask is not None
                        _websocket_mask(self._frame_mask, payload)

                    frames.append((
                        self._frame_fin,
                        self._frame_opcode,
                        payload,
                        self._compressed))

                    self._frame_payload = bytearray()
                    self._state = WSParserState.READ_HEADER
                else:
                    break

        self._tail = buf[start_pos:]

        return frames
1278712
private void processHeader() {
    int type = nextFrame.readUnsignedByte();
    if ((type & RESERVED_MASK) != 0) {
      throw Status.INTERNAL.withDescription(
          "gRPC frame header malformed: reserved bits not zero")
          .asRuntimeException();
    }
    compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;

    // Update the required length to include the length of the frame.
    requiredLength = nextFrame.readInt();
    if (requiredLength < 0 || requiredLength > maxInboundMessageSize) {
      throw Status.RESOURCE_EXHAUSTED.withDescription(
          String.format("gRPC message exceeds maximum size %d: %d",
              maxInboundMessageSize, requiredLength))
          .asRuntimeException();
    }

    currentMessageSeqNo++;
    statsTraceCtx.inboundMessage(currentMessageSeqNo);
    transportTracer.reportMessageReceived();
    // Continue reading the frame body.
    state = State.BODY;
  }
670479
def parse_content_type(header):
    """"""
    typ = subtyp = None; options = {}
    typ, pos = expect_re(re_token, header, 0)
    _, pos = expect_lit('/', header, pos)
    subtyp, pos = expect_re(re_token, header, pos)
    ctype = header[:pos] if subtyp else ''
    while pos < len(header):
        _, pos = accept_ws(header, pos)
        _, pos = expect_lit(';', header, pos)
        _, pos = accept_ws(header, pos)
        name, pos = expect_re(re_token, header, pos)
        _, pos = expect_lit('=', header, pos)
        char = lookahead(header, pos)
        if char == '"':
            value, pos = expect_re(re_qstring, header, pos)
            value = re_qpair.sub('\\1', value)
        elif char:
            value, pos = expect_re(re_token, header, pos)
        if name and value is not None:
            options[name] = value
    return ctype, options
662167
def parse_payload(data, payload_fmt, *payload_names):
    
    payload = struct.unpack(payload_fmt, data)
    return dict(zip(payload_names, payload))
185811
def header_from_raw_header_data(cls, raw_header):
        
        try:
            header = MessageHeader(*cls.header_struct.unpack(raw_header))
        except struct.error:
            raise Exception("Invalid message header received")
        return header
926732
def pack_into(self, buf, offset, write_payload):
    
    return self._get_framed(buf, offset, write_payload)
172052
def recv(stream):
    """"""
    header = stream.read(4)
    if len(header) != 4:
        return None # EOF
    (length,) = struct.unpack('!I', header)
    payload = stream.read(length)
    if len(payload) != length:
        return None
    term = erlang.binary_to_term(payload)
    return term
29034
def parse_dbus_header(header):
    """"""
    if six.indexbytes(header, 0) == ord('l'):
        endian = '<'
    elif six.indexbytes(header, 0) == ord('B'):
        endian = '>'
    else:
        raise ValueError('illegal endianness')
    if not 1 <= six.indexbytes(header, 1) <= 4:
        raise ValueError('illegel message type')
    if struct.unpack(endian + 'I', header[8:12])[0] == 0:
        raise ValueError('illegal serial number')
    harrlen = struct.unpack(endian + 'I', header[12:16])[0]
    padlen = (8 - harrlen) % 8
    bodylen = struct.unpack(endian + 'I', header[4:8])[0]
    return 16 + harrlen + padlen + bodylen
778376
def _parseAtFrame(self, src):
        
        src = src[len('@frame '):].lstrip()
        box, src = self._getIdent(src)
        src, properties = self._parseDeclarationGroup(src.lstrip())
        result = [self.cssBuilder.atFrame(box, properties)]
        return src.lstrip(), result
616888
def decode_payload_as(self,cls):
        """"""
        s = bytes(self.payload)
        self.payload = cls(s, _internal=1, _underlayer=self)
        pp = self
        while pp.underlayer is not None:
            pp = pp.underlayer
        self.payload.dissection_done(pp)
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
994842
def parse_packet(data, format=None):
    
    unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
    psize, protocol, mac, gateway, time, ptype = unpacked
    header = Header(psize, protocol, mac, gateway, time, ptype)
    return header, data[_FORMAT_SIZE:]