[编织消息框架][netty源码分析]13 ByteBuf 实现类CompositeByteBuf职责与实现
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实现
作者: | solq |
博客地址: | http://www.cnblogs.com/solq111 |
博客版权: | 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。 如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。 淘宝店: 海豚极货店 QQ群:9547527 ![]() |
如果你热爱生活、热爱编程、热爱吉他。扫一扫加我微信 ![]() |
我的新书《编织消息框架》目前进行中,感谢大家关注! |
![]() |