Allocate a {@link ByteBuf} which will be used as argument of {@link #encode(ChannelHandlerContext, I, ByteBuf)}.
Sub-classes may override this method to return {@link ByteBuf} with a perfect matching {@code initialCapacity}.
346555
protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, @SuppressWarnings("unused") I msg,
                               boolean preferDirect) throws Exception {
        if (preferDirect) {
            return ctx.alloc().ioBuffer();
        } else {
            return ctx.alloc().heapBuffer();
        }
    }
3410
@SuppressWarnings("deprecation")
    public static ByteBuf writeMediumBE(ByteBuf buf, int mediumValue) {
        return buf.order() == ByteOrder.BIG_ENDIAN? buf.writeMedium(mediumValue) : buf.writeMediumLE(mediumValue);
    }
786821
public void encode(ByteBuf buf) {

        buf.writeByte('*');
        CommandArgs.IntegerArgument.writeInteger(buf, 1 + (args != null ? args.count() : 0));

        buf.writeBytes(CommandArgs.CRLF);

        CommandArgs.BytesArgument.writeBytes(buf, type.getBytes());

        if (args != null) {
            args.encode(buf);
        }
    }
376347
@Override
    public synchronized CommsServerByteBuffer allocate() {
        if (tc.isEntryEnabled())
            SibTr.entry(this, tc, "allocate");

        CommsServerByteBuffer buff = (CommsServerByteBuffer) super.allocate();

        if (tc.isEntryEnabled())
            SibTr.exit(this, tc, "allocate", buff);
        return buff;
    }
1310583
public synchronized ByteBuffer allocateHeaderBuffer() {
        Stack<ByteBuffer> pool = pools.get(HEADER_SIZE);
        if (pool.isEmpty()) {
            return ByteBuffer.allocate(HEADER_SIZE);
        } else {
            return pool.pop();
        }
    }
1354804
public <T extends CacheSpec<K, V>> T initialCapacity(int initialCapacity) {
      checkArgument(initialCapacity > 0, "Capacity must be > 0");
      this.initialCapacity = initialCapacity;
      return Cast.as(this);
   }
1164952
public static ByteBuf serialize(final Serializable serializable) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();;
        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(serializable);

        byte[] serialized = bos.toByteArray();
        os.close();
        bos.close();
        return Unpooled.buffer().writeBytes(serialized);
    }
568085
public static ByteBuffer allocate(int capacity) {
        ByteBuffer buf = ByteBuffer.allocate(capacity);
        buf.limit(0);
        return buf;
    }
654064
public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        SimplePacket helloPacket  = (SimplePacket) packet;
        byte[] body = helloPacket.getBody();
        int bodyLen = 0;
        if(body != null){
            bodyLen = body.length;
        }

        //Bytebuffer总长度 = 消息头+消息体的长度
        int allLen = SimplePacket.HEADER_LENGTH+bodyLen;
        //创建新的Bytebuffer
        ByteBuffer buf = ByteBuffer.allocate(allLen);
        //设置字节序
        buf.order(groupContext.getByteOrder());
        //写入消息头
        buf.putInt(bodyLen);
        //写入消息体
        if(body != null){
            buf.put(body);
        }
        return buf;
    }
568732
synchronized public int encodeIntoByteBuffer(final ByteBuffer buffer) {
        final long maxValue = getMaxValue();
        final int relevantLength = countsArrayIndex(maxValue) + 1;
        if (buffer.capacity() < getNeededByteBufferCapacity(relevantLength)) {
            throw new ArrayIndexOutOfBoundsException("buffer does not have capacity for " +
                    getNeededByteBufferCapacity(relevantLength) + " bytes");
        }
        int initialPosition = buffer.position();
        buffer.putInt(getEncodingCookie());
        buffer.putInt(0); // Placeholder for payload length in bytes.
        buffer.putInt(getNormalizingIndexOffset());
        buffer.putInt(numberOfSignificantValueDigits);
        buffer.putLong(lowestDiscernibleValue);
        buffer.putLong(highestTrackableValue);
        buffer.putDouble(getIntegerToDoubleValueConversionRatio());

        int payloadStartPosition = buffer.position();
        fillBufferFromCountsArray(buffer);
        buffer.putInt(initialPosition + 4, buffer.position() - payloadStartPosition); // Record the payload length


        return buffer.position() - initialPosition;
    }
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();
    }
179428
private long allocateRun(int normCapacity) {
        int d = maxOrder - (log2(normCapacity) - pageShifts);
        int id = allocateNode(d);
        if (id < 0) {
            return id;
        }
        freeBytes -= runLength(id);
        return id;
    }
456236
public ByteBuffer readToByteBuffer(int max) throws IOException {
        Validate.isTrue(max >= 0, "maxSize must be 0 (unlimited) or larger");
        final boolean localCapped = max > 0; // still possibly capped in total stream
        final int bufferSize = localCapped && max < DefaultSize ? max : DefaultSize;
        final byte[] readBuffer = new byte[bufferSize];
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);

        int read;
        int remaining = max;

        while (true) {
            read = read(readBuffer);
            if (read == -1) break;
            if (localCapped) { // this local byteBuffer cap may be smaller than the overall maxSize (like when reading first bytes)
                if (read >= remaining) {
                    outStream.write(readBuffer, 0, remaining);
                    break;
                }
                remaining -= read;
            }
            outStream.write(readBuffer, 0, read);
        }
        return ByteBuffer.wrap(outStream.toByteArray());
    }
329737
public ByteBuffer toByteBuffer() {
    // Allow room for encoded message, plus the type byte
    ByteBuf buf = Unpooled.buffer(encodedLength() + 1);
    buf.writeByte(type().id);
    encode(buf);
    assert buf.writableBytes() == 0 : "Writable bytes remain: " + buf.writableBytes();
    return buf.nioBuffer();
  }
1219427
@Override
    public AllocationPoint allocateMemory(DataBuffer buffer, AllocationShape requiredMemory, boolean initialize) {
        // by default we allocate on initial location
        AllocationPoint point = null;

        if (configuration.getMemoryModel() == Configuration.MemoryModel.IMMEDIATE) {
            point = allocateMemory(buffer, requiredMemory, memoryHandler.getInitialLocation(), initialize);
        } else if (configuration.getMemoryModel() == Configuration.MemoryModel.DELAYED) {
            // for DELAYED memory model we allocate only host memory, regardless of firstMemory configuration value
            point = allocateMemory(buffer, requiredMemory, AllocationStatus.HOST, initialize);
        }

        return point;
    }
1089483
WrappedByteBuffer expandAt(int i, int expectedRemaining) {
        if ((i + expectedRemaining) <= _buf.limit()) {
            return this;
        } else {
            if ((i + expectedRemaining) <= _buf.capacity()) {
                _buf.limit(i + expectedRemaining);
            } else {
                // reallocate the underlying byte buffer and keep the original buffer
                // intact. The resetting of the position is required because, one
                // could be in the middle of a read of an existing buffer, when they
                // decide to over write only few bytes but still keep the remaining
                // part of the buffer unchanged.
                int newCapacity = _buf.capacity()
                        + ((expectedRemaining > INITIAL_CAPACITY) ? expectedRemaining : INITIAL_CAPACITY);
                java.nio.ByteBuffer newBuffer = java.nio.ByteBuffer.allocate(newCapacity);
                _buf.flip();
                newBuffer.put(_buf);
                _buf = newBuffer;
            }
        }

        return this;
    }
399802
public ByteBuffer toThrift() {
    Buffer buffer = Buffer.allocate(sizeInBytes());
    write(buffer);
    return ByteBuffer.wrap(buffer.toByteArray());
  }