zoukankan      html  css  js  c++  java
  • [编织消息框架][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实现

  • 相关阅读:
    爬虫笔记(四)------关于BeautifulSoup4解析器与编码
    sublime_text_2 ubuntu下无法输入中文 解决方法
    PHP 随手记
    PHP与apache环境配置
    5分钟学会如何创建spring boot项目
    Java 解压zip压缩包
    利用JavaScript来实现用动态检验密码强度
    金融行业是如何丢失1分钱的
    Java多线程的三种实现方式
    教你如何快速定制 SpringBoot banner
  • 原文地址:https://www.cnblogs.com/solq111/p/7112404.html
Copyright © 2011-2022 走看看