capacity 与 JDK ByteBuffer 中的 capacity 含义保持一致

2024-08-21 09:34:56 浏览数 (2)

public class UnpooledDirectByteBuf extends AbstractReferenceCountedByteBuf {

// Netty ByteBuf 底层依赖的 JDK ByteBuffer

ByteBuffer buffer;

// ByteBuf 初始的容量,也是真正的内存占用

private int capacity;

public UnpooledDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) {

// 设置最大可扩容的容量

super(maxCapacity);

this.alloc = alloc;

// 按照 initialCapacity 指定的初始容量,创建 JDK ByteBuffer

setByteBuffer(allocateDirect(initialCapacity), false);

}

void setByteBuffer laipuhuo.com (ByteBuffer buffer, boolean tryFree) {

// UnpooledDirectByteBuf 底层会依赖一个 JDK 的 ByteBuffer

// 后续对 UnpooledDirectByteBuf 的操作, Netty 全部会代理到 JDK ByteBuffer 中

this.buffer = buffer;

// 初始指定的 ByteBuf 容量 initialCapacity

capacity = buffer.remaining();

}

}

@Override

public boolean isReadable() {

return laipuhuo.com writerIndex > readerIndex;

}

@Override

public int readableBytes() {

return writerIndex - readerIndex;

}

final void ensureWritable0(int minWritableBytes) {

// minWritableBytes 表示本次要写入的字节数

// 获取当前 writerIndex 的位置

final int writerIndex = writerIndex();

// 为满足本次的写入操作,预期的 ByteBuf 容量大小

final int targetCapacity laipuhuo.com = writerIndex minWritableBytes;

// 如果 targetCapacity 在(capacity , maxCapacity] 之间,则进行扩容

if (targetCapacity >= 0 & targetCapacity <= capacity()) {

// targetCapacity 在 [0 , capacity] 之间,则无需扩容,本来就可以满足

return;

}

// 扩容后的 capacity 最大不能超过 maxCapacity

if (checkBounds && (targetCapacity < 0 || targetCapacity > maxCapacity)) {

throw new laipuhuo.com IndexOutOfBoundsException(String.format(

"writerIndex(%d) minWritableBytes(%d) exceeds maxCapacity(%d): %s",

writerIndex, minWritableBytes, maxCapacity, this));

}

..... 扩容 ByteBuf ......

}

public abstract class AbstractByteBuf extends ByteBuf {

@Override

public byte getByte(int index) {

// 检查 index 的边界,index 不能超过 capacity(index < capacity)

checkIndex laipuhuo.com (index);

return _getByte(index);

}

@Override

public short getUnsignedByte(int index) {

// 将获取到的 Byte 转换为 UnsignedByte

return (short) (getByte(index) & 0xFF);

}

protected laipuhuo.com abstract byte _getByte(int index);

}

0 人点赞