Reads a message from the given ByteBuffer and returns it.
518214
@Override
    public Message deserialize(ByteBuffer in) throws ProtocolException, IOException {
        // A Bitcoin protocol message has the following format.
        //
        //   - 4 byte magic number: 0xfabfb5da for the testnet or
        //                          0xf9beb4d9 for production
        //   - 12 byte command in ASCII
        //   - 4 byte payload size
        //   - 4 byte checksum
        //   - Payload data
        //
        // The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't
        // present for all messages, notably, the first one on a connection.
        //
        // Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because
        // sometimes it sends us stuff that isn't part of any message.
        seekPastMagicBytes(in);
        BitcoinPacketHeader header = new BitcoinPacketHeader(in);
        // Now try to read the whole message.
        return deserializePayload(header, in);
    }
704424
def read(self):
        """"""
        data = bytearray()
        while True:
            incoming_bytes = self.comport.inWaiting()
            if incoming_bytes == 0:
                break
            else:
                content = self.comport.read(size=incoming_bytes)
                data.extend(bytearray(content))
        return data
712232
def read_bytes(self, num_bytes):
        """"""
        buffer_size = len(self._buffer)
        if buffer_size > num_bytes:
            # The buffer is larger than the requested amount of bytes.
            data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:]
        elif 0 < buffer_size <= num_bytes:
            # This might return less bytes than requested.
            data, self._buffer = self._buffer, bytearray()
        else:
            # Buffer is empty. Try to read `num_bytes` and call `read_bytes()`
            # again. This ensures that at most `num_bytes` are returned.
            self._buffer += self.__read__(num_bytes)
            return self.read_bytes(num_bytes)
        return data
77946
public ByteBuffer readBuffer(final int byteLen) {
        final byte[] data = new byte[byteLen];
        buffer.get(data);
        return ByteBuffer.wrap(data);
    }
240986
private void receiveMessage(ClientSocket client, DataInputStream buffer, byte from, StateConnection expected)
            throws IOException
    {
        if (ServerImpl.checkValidity(client, from, expected))
        {
            final byte dest = buffer.readByte();
            final byte type = buffer.readByte();
            final int size = buffer.readInt();
            if (size > 0)
            {
                final byte[] clientData = new byte[size];
                if (buffer.read(clientData) != -1) // CHECKSTYLE IGNORE LINE: TrailingComment|NestedIfDepth
                {
                    final DataInputStream clientBuffer = new DataInputStream(new ByteArrayInputStream(clientData));
                    decodeMessage(type, from, dest, clientBuffer);
                }
            }
            final int headerSize = 4;
            bandwidth += headerSize + size;
        }
    }
476725
public static InputStream byteBufferToInputStream(final ByteBuffer byteBuffer) {
        // https://stackoverflow.com/questions/4332264/wrapping-a-bytebuffer-with-an-inputstream/6603018#6603018
        return new InputStream() {
            /** The intermediate buffer. */
            final ByteBuffer buf = byteBuffer;

            @Override
            public int read() {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                return buf.get() & 0xFF;
            }

            @Override
            public int read(final byte[] bytes, final int off, final int len) {
                if (!buf.hasRemaining()) {
                    return -1;
                }

                final int bytesRead = Math.min(len, buf.remaining());
                buf.get(bytes, off, bytesRead);
                return bytesRead;
            }
        };
    }
20263
def message_from_bytes(s, *args, **kws):
    
    from future.backports.email.parser import BytesParser
    return BytesParser(*args, **kws).parsebytes(s)
566661
public int read(byte []buffer, int offset, int length)
    throws IOException
  {
    return _file.read(buffer, offset, length);
  }
126217
def read_message(self, message_type, compressed=False, read_size=True):
        
        if read_size:
            size = self.read_vint32()
            b = self.read(size)
        else:
            b = self.read()

        if compressed:
            b = snappy.decompress(b)

        m = message_type()
        m.ParseFromString(b)
        return m
188019
@Override
    public int read(final ByteBuffer destination) throws IOException {

        // Precondition checks
        this.checkClosed();
        if (destination == null) {
            throw new IllegalArgumentException("Destination buffer must be supplied");
        }

        // Init
        final int spaceInBuffer = destination.remaining();
        final int numBytesRemainingInContent, numBytesToRead;

        // Sync up before getting at shared mutable state
        synchronized (this) {
            numBytesRemainingInContent = this.contents.length - this.position;

            // Set position was greater than the size? Just return.
            if (numBytesRemainingInContent <= 0) {
                return -1;
            }

            // We'll read in either the number of bytes remaining in content or the amount of space in the buffer,
            // whichever is smaller
            numBytesToRead = numBytesRemainingInContent >= spaceInBuffer ? spaceInBuffer : numBytesRemainingInContent;
            // Copy a sub-array of the bytes we'll put into the buffer
            destination.put(this.contents, this.position, numBytesToRead);

            // Set the new position
            this.position += numBytesToRead;
        }

        // Return the number of bytes read
        return numBytesToRead;
    }
154743
@Override
    public byte[] read(ScanBuffer buffer) {
        int length = getLength(buffer);
        if (length<0) return null;
        return buffer.getBytes(length);
    }
257198
@Override
    public ByteBuffer readBytes(int numBytes) throws IOException {
        final int appsz = applicationBufferSize();
        ByteBuf readbuf = m_ce.allocator().ioBuffer(packetBufferSize());
        CompositeByteBuf msgbb = Unpooled.compositeBuffer();

        try {
            ByteBuf clear = doUnwrap(readbuf, appsz);

            msgbb.addComponent(true, clear);
            int needed = numBytes;
            if (numBytes == NOT_AVAILABLE) {
                needed = msgbb.readableBytes() >= 4 ? validateLength(msgbb.readInt()) : NOT_AVAILABLE;
            }
            while (msgbb.readableBytes() < (needed == NOT_AVAILABLE ? 4 : needed)) {
                clear = doUnwrap(readbuf, appsz);

                msgbb.addComponent(true, clear);

                if (needed == NOT_AVAILABLE && msgbb.readableBytes() >= 4) {
                    needed = validateLength(msgbb.readInt());
                }
            }

            ByteBuffer retbb = ByteBuffer.allocate(needed);
            msgbb.readBytes(retbb);
            msgbb.discardReadComponents();

            assert !msgbb.isReadable() : "read from unblocked channel that received multiple messages?";

            return (ByteBuffer)retbb.flip();
        } finally {
            readbuf.release();
            msgbb.release();
        }
    }
99920
public static String readString(ByteBuffer buf) {
        if(buf.get() == 0)
            return null;
        int len=readInt(buf);
        if(buf.isDirect()) {
            byte[] bytes=new byte[len];
            buf.get(bytes);
            return new String(bytes);
        }
        else {
            byte[] bytes=buf.array();
            return new String(bytes, buf.arrayOffset() + buf.position(), len);
        }
    }
732823
protected static ByteBuffer toTCPBuffer(GelfMessage message, ThreadLocal<ByteBuffer> writeBuffers) {

        while (true) {

            try {
                return message.toTCPBuffer(getBuffer(writeBuffers));
            } catch (BufferOverflowException e) {
                enlargeBuffer(writeBuffers);
            }
        }
    }
265004
static int fillBufferWithDelimitedMessageFrom(InputStream in,
            boolean drainRemainingBytesIfTooLarge,
            LinkedBuffer lb) throws IOException
    {
        final byte[] buf = lb.buffer;
        int offset = lb.start, len = buf.length - offset, read = in.read(buf, offset, len);

        if (read < 1)
            throw new EOFException("fillBufferWithDelimitedMessageFrom");

        int last = offset + read, size = buf[offset++];
        if (0 != (size & 0x80))
        {
            size = size & 0x7f;

            for (int shift = 7;; shift += 7)
            {
                if (offset == last)
                {
                    // read too few bytes
                    read = in.read(buf, last, len - (last - lb.start));
                    if (read < 1)
                        throw new EOFException("fillBufferWithDelimitedMessageFrom");

                    last += read;
                }

                byte b = buf[offset++];
                size |= (b & 0x7f) << shift;

                if (0 == (b & 0x80))
                    break;

                if (shift == 28)
                {
                    // discard the remaining bytes (5)
                    for (int i = 0;;)
                    {
                        if (offset == last)
                        {
                            // read more
                            read = in.read(buf, last, len - (last - lb.start));
                            if (read < 1)
                                throw new EOFException("fillBufferWithDelimitedMessageFrom");

                            last += read;
                        }

                        if (buf[offset++] >= 0)
                            break;

                        if (5 == ++i)
                        {
                            // we've already consumed 10 bytes
                            throw ProtobufException.malformedVarint();
                        }
                    }

                }
            }
        }

        if (size == 0)
        {
            if (offset != last)
                throw ProtobufException.misreportedSize();

            return size;
        }

        if (size < 0)
            throw ProtobufException.negativeSize();

        final int partial = last - offset;
        if (partial < size)
        {
            // need to read more
            final int delimSize = offset - lb.start;
            if ((size + delimSize) > len)
            {
                // too large.

                if (!drainRemainingBytesIfTooLarge)
                    return size;

                // drain the remaining bytes
                for (int remaining = size - partial; remaining > 0;)
                {
                    read = in.read(buf, lb.start, Math.min(remaining, len));
                    if (read < 1)
                        throw new EOFException("fillBufferWithDelimitedMessageFrom");

                    remaining -= read;
                }

                return size;
            }

            // read the remaining bytes
            fillBufferFrom(in, buf, last, size - partial);
        }

        // set the read offset (start of message)
        lb.offset = offset;

        return size;
    }
417671
private byte nextByte(ByteBuffer inputBuffer) throws IOException {
        getAtLeastBytes(inputBuffer, 1, ReadMode.ONLY_WHEN_EMPTY);
        return inputBuffer.get();
    }
230898
def _read_msg(self):
        """"""

        #
        # NOTE:
        # '_recv_socket(nbytes)' was implemented as
        # 'socket.recv(nbytes, socket.MSG_WAITALL)'
        # but socket.MSG_WAITALL proved not reliable
        #

        def _recv_socket(nbytes):
            """read nbytes bytes from self.socket"""

            #
            # code below is written under the assumption that
            # 'nbytes' is smallish so that the 'while len(buf) < nbytes' loop
            # is entered rarerly
            #
            try:
                buf = self.socket.recv(nbytes)
            except IOError as err:
                raise ConnError(*err.args)

            if not buf:
                raise ShortRead(0, nbytes)

            while len(buf) < nbytes:
                try:
                    tmp = self.socket.recv(nbytes - len(buf))
                except IOError as err:
                    raise ConnError(*err.args)

                if not tmp:
                    if self.verbose:
                        print('ee', repr(buf))
                    raise ShortRead(len(buf), nbytes)

                buf += tmp

            assert len(buf) == nbytes, (buf, len(buf), nbytes)
            return buf

        data = _recv_socket(_FromServerHeader.header_size)
        header = _FromServerHeader(data)
        if self.verbose:
            print('<-', repr(header))

        # error conditions
        if header.version != 0:
            raise MalformedHeader('bad version', header)
        if header.payload > MAX_PAYLOAD:
            raise MalformedHeader('huge payload, unwilling to read', header)

        if header.payload > 0:
            payload = _recv_socket(header.payload)
            if self.verbose:
                print('..', repr(payload))
            assert header.size <= header.payload
            payload = payload[:header.size]
        else:
            payload = bytes()
        return header, payload