[编织消息框架][netty源码分析]13 ByteBuf 实现类CompositeByteBuf职责与实现

时间:2021-04-12 00:47:36
public class CompositeByteBuf extends AbstractReferenceCountedByteBuf implements Iterable<ByteBuf> {

    private final ByteBufAllocator alloc;
private final boolean direct;
//组合内容
private final List<Component> components; //内部类Component,指针记录
private static final class Component {
final ByteBuf buf;
final int length;
int offset;
int endOffset; Component(ByteBuf buf) {
this.buf = buf;
length = buf.readableBytes();
} void freeIfNecessary() {
buf.release(); // We should not get a NPE here. If so, it must be a bug.
}
}
//Iterator 实现,只要实现hasNext跟next,维护nextIndex即可
private final class CompositeByteBufIterator implements Iterator<ByteBuf> {
private final int size = components.size();
private int index; @Override
public boolean hasNext() {
return size > index;
} @Override
public ByteBuf next() {
if (size != components.size()) {
throw new ConcurrentModificationException();
}
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return components.get(index++).buf;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
} //由于readBytes跟writeBytes逻辑差不多,r/w时先定位那个component之后再进行操作
//这里用到二分查找法
public int toComponentIndex(int offset) {
checkIndex(offset); for (int low = 0, high = components.size(); low <= high;) {
int mid = low + high >>> 1; //>>>1 无符号右移1位 相当于high/2
Component c = components.get(mid);
//在右半边
if (offset >= c.endOffset) {
low = mid + 1;
} else if (offset < c.offset) { //在左半边
high = mid - 1;
} else {
return mid;
}
} throw new Error("should not reach here");
}
}

小结:

由于CompositeByteBuf太部份逻辑处理是对区块处理,不具有分析价值,本人认为有价值部分为二分查找算法实践同Iterable实现