Returns the {@link ProtocolDetectionResult} for the given {@link ByteBuf}.
338699
public static ProtocolDetectionResult<HAProxyProtocolVersion> detectProtocol(ByteBuf buffer) {
        if (buffer.readableBytes() < 12) {
            return ProtocolDetectionResult.needsMoreData();
        }

        int idx = buffer.readerIndex();

        if (match(BINARY_PREFIX, buffer, idx)) {
            return DETECTION_RESULT_V2;
        }
        if (match(TEXT_PREFIX, buffer, idx)) {
            return DETECTION_RESULT_V1;
        }
        return ProtocolDetectionResult.invalid();
    }
1278700
@Override
  public NamingLookupResponse decode(final byte[] buf) {
    final AvroNamingLookupResponse avroResponse = AvroUtils.fromBytes(buf, AvroNamingLookupResponse.class);
    final List<NameAssignment> nas = new ArrayList<>(avroResponse.getTuples().size());
    for (final AvroNamingAssignment tuple : avroResponse.getTuples()) {
      nas.add(
          new NameAssignmentTuple(
              factory.getNewInstance(tuple.getId().toString()),
              new InetSocketAddress(tuple.getHost().toString(), tuple.getPort())
          )
      );
    }
    return new NamingLookupResponse(nas);
  }
269523
@Override
  public NamingUnregisterRequest decode(final byte[] buf) {
    final AvroNamingUnRegisterRequest result = AvroUtils.fromBytes(buf, AvroNamingUnRegisterRequest.class);
    return new NamingUnregisterRequest(factory.getNewInstance(result.getId().toString()));
  }
1177192
private int read(ByteBuffer buf)
    {
        int nbytes;
        try {
            nbytes = fd.read(buf);
            if (nbytes == -1) {
                errno.set(ZError.ENOTCONN);
            }
            else if (nbytes == 0) {
                if (!fd.isBlocking()) {
                    //  If not a single byte can be read from the socket in non-blocking mode
                    //  we'll get an error (this may happen during the speculative read).

                    //  Several errors are OK. When speculative read is being done we may not
                    //  be able to read a single byte from the socket. Also, SIGSTOP issued
                    //  by a debugging tool can result in EINTR error.
                    errno.set(ZError.EAGAIN);
                    nbytes = -1;
                }
            }
        }
        catch (IOException e) {
            errno.set(ZError.ENOTCONN);
            nbytes = -1;
        }

        return nbytes;
    }
1141917
public static byte[] asByteArray(ByteBuffer buf) {
        byte[] result;
        if (buf.hasArray() && buf.arrayOffset() == 0 && buf.capacity() == buf.remaining()) {
            result = buf.array();
        }
        else {
            result = new byte[buf.remaining()];
            if (buf.hasArray()) {
                System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), result, 0, result.length);
            }
            else {
                // Direct buffer
                ByteBuffer duplicate = buf.duplicate();
                duplicate.mark();
                duplicate.get(result);
                duplicate.reset();
            }
        }
        return result;
    }
1032268
public final ProtocolType getGuaranteedProtocolType() {
        Byte value = (Byte) getHdr2().getField(JsHdr2Access.GUARANTEED_SET_PROTOCOLTYPE);
        return ProtocolType.getProtocolType(value);
    }
1256760
@Override
    public ByteBuffer read(ByteBuffer receiveBuffer) throws IOException {
        if (!doHandshake(receiveBuffer))
            return null;

        if (!initialHSComplete)
            throw new IllegalStateException("The initial handshake is not complete.");

        if (log.isDebugEnabled()) {
            log.debug("session {} read data status -> {}, initialHSComplete -> {}", session.getSessionId(),
                    session.isOpen(), initialHSComplete);
        }

        merge(receiveBuffer);
        if (!receivedPacketBuf.hasRemaining()) {
            return null;
        }

        needIO:
        while (true) {
            SSLEngineResult result = unwrap();

            if (log.isDebugEnabled()) {
                log.debug("Session {} read data result -> {}, receivedPacketBuf -> {}, appBufSize -> {}",
                        session.getSessionId(), result.toString().replace('\n', ' '),
                        receivedPacketBuf.remaining(), receivedAppBuf.remaining());
            }

            switch (result.getStatus()) {
                case BUFFER_OVERFLOW: {
                    resizeAppBuffer();
                    // retry the operation.
                }
                break;
                case BUFFER_UNDERFLOW: {
                    int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                    if (receivedPacketBuf.remaining() >= packetBufferSize) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }
                case OK: {
                    if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                        doTasks();
                    }
                    if (receivedPacketBuf.hasRemaining()) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }

                case CLOSED: {
                    log.info("Session {} read data failure. SSLEngine will close inbound", session.getSessionId());
                    closeInbound();
                }
                break needIO;

                default:
                    throw new SecureNetException(StringUtils.replace("Session {} SSLEngine read data exception. status -> {}",
                            session.getSessionId(), result.getStatus()));
            }
        }

        return getReceivedAppBuf();
    }
527081
public static ProtocolSignature getProtocolSignature(
      int clientMethodsHashCode,
      long serverVersion,
      Class<? extends VersionedProtocol> protocol) {
    // try to get the finger print & signature from the cache
    ProtocolSigFingerprint sig = getSigFingerprint(protocol, serverVersion);
    
    // check if the client side protocol matches the one on the server side
    if (clientMethodsHashCode == sig.fingerprint) {
      return new ProtocolSignature(serverVersion, null);  // null indicates a match
    } 
    
    return sig.signature;
  }
709875
public synchronized void returnBuf(byte[] buf) {
        if (buf == null || buf.length > mSizeLimit) {
            return;
        }
        mBuffersByLastUse.add(buf);
        int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
        if (pos < 0) {
            pos = -pos - 1;
        }
        mBuffersBySize.add(pos, buf);
        mCurrentSize += buf.length;
        trim();
    }
636668
public static byte[] readRawBytes(ByteBuf cb)
    {
        byte[] bytes = new byte[cb.readableBytes()];
        cb.readBytes(bytes);
        return bytes;
    }
87304
@Nullable
	@Contract(pure = true)
	public ByteBuf peekBuf() {
		return hasRemaining() ? bufs[first] : null;
	}
917893
public static Byte getByte(byte pValue) {
        if (pValue >= BYTE_LOWER_BOUND &&
                pValue <= BYTE_UPPER_BOUND) {
            return mBytes[((int) pValue) - BYTE_LOWER_BOUND];
        } else {
            return new Byte(pValue);
        }
    }
1136118
public ChannelFuture respondBinary(ByteBuf byteBuf) throws Exception {
        if (HttpUtil.isTransferEncodingChunked(response)) {
            respondHeadersOnlyForFirstChunk();
            return channel.writeAndFlush(new DefaultHttpContent(byteBuf));
        } else {
            if (!response.headers().contains(CONTENT_TYPE))
                response.headers().set(CONTENT_TYPE, "application/octet-stream");

            response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
            response.content().writeBytes(byteBuf);
            return respond();
        }
    }
55060
public static Protocol getProtocol(byte code) {
        Protocol protocol = TYPE_PROTOCOL_MAP.get(code);
        if (protocol == null) {
            throw new SofaRpcRuntimeException("Extension Not Found :\"" + code + "\"!");
        }
        return protocol;
    }
458945
public byte[] getBytes() {
        byte[] retval = new byte[buffer.b().position()];
        int position = buffer.b().position();
        buffer.b().rewind();
        buffer.b().get(retval);
        assert position == buffer.b().position();
        return retval;
    }
258124
public static int decodeSequence(ByteBuffer buf) {
        DerId id = DerId.decode(buf);
        if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.CONSTRUCTED, ASN1_SEQUENCE_TAG_NUM)) {
            throw new IllegalArgumentException("Expected SEQUENCE identifier, received " + id);
        }
        int len = DerUtils.decodeLength(buf);
        if (buf.remaining() < len) {
            throw new IllegalArgumentException("Insufficient content for SEQUENCE");
        }
        return len;
    }
907828
private NetProtocol checkProtocol(String protocol)
    {
        //  First check out whether the protcol is something we are aware of.
        NetProtocol proto = NetProtocol.getProtocol(protocol);
        if (proto == null || !proto.valid) {
            errno.set(ZError.EPROTONOSUPPORT);
            return proto;
        }

        //  Check whether socket type and transport protocol match.
        //  Specifically, multicast protocols can't be combined with
        //  bi-directional messaging patterns (socket types).
        if (!proto.compatible(options.type)) {
            errno.set(ZError.ENOCOMPATPROTO);
            return null;
        }
        //  Protocol is available.
        return proto;
    }