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实现

  • 相关阅读:
    ASP.NET MVC preview 1升级到ASP.NET MVC preview 2的一些更改
    今天遇到一个非常奇怪的问题
    Microsoft ASP.NET MVC中Membership登陆的实现
    自己用的一个ASP.Net MVC分页拿出来分享下
    KnockoutJs学习笔记(一)
    KnockoutJs学习笔记(三)
    KnockoutJs学习笔记(二)
    KnockoutJs学习笔记(四)
    学习网站不定期更新
    一些好的网站
  • 原文地址:https://www.cnblogs.com/solq111/p/7112404.html
Copyright © 2011-2022 走看看