吃透Netty源码系列三十六之CompositeByteBuf详解二

本文深入解析Netty中CompositeByteBuf的组件删除、数据读取、组件查找及二分搜索等核心操作,详细介绍其内部实现机制,包括removeComponent、getByte、findComponent、findIt、toComponentIndex、addFlattenedComponents、iterator、isDirect、capacity和deallocate等方法。

removeComponent删除组件

前一篇讲了新增操作,接下来讲讲其他的,首先当然是删除啦,删除索引对应的缓冲区。原理就是获取对应的组件,然后释放,然后从组件数组中删除

  public CompositeByteBuf removeComponent(int cIndex) {
   
   
        checkComponentIndex(cIndex);
        Component comp = components[cIndex];
        if (lastAccessed == comp) {
   
   //查找的时候缓存用的
            lastAccessed = null;
        }
        comp.free();//释放缓冲区
        removeComp(cIndex);//删除组件
        if (comp.length() > 0) {
   
   //如果有可读数据被删除了,那就需要更新之后的组件索引
            updateComponentOffsets(cIndex);
        }
        return this;
    }
//删除索引对应的组件
    private void removeComp(int i) {
   
   
        removeCompRange(i, i + 1);
    }

getByte获取数据

增删讲完了,该说说读和写吧,获取指定索引的字节数据。

  @Override
    public byte getByte(int index) {
   
   
        Component c = findComponent(index);
        return c.buf.getByte(c.idx(index));//根据索引获取字节数据
    }

findComponent查找组件

如果缓存的那个索引区域就是我们要找的,就直接返回去,否则就要去找。

    private Component findComponent(int offset) {
   
   
        Component la = lastAccessed;//缓存的
        if (la != null && offset >= la.offset && offset < la.endOffset) {
   
   //索引在缓存组件内
           ensureAccessible();
           return la;
        }
        checkIndex(offset);
        return findIt(offset);
    }

findIt二分查找

二分查找法查找,找到的组件会缓存到lastAccessed

private Component findIt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值