• netty(八)buffer源码学习3


    问题 :

    • compositeByteBuf 是干什么和其他 compositeByteBuf 有何区别
    • 内部实现

    概述

    compositeByteBuf 就像数据库中的视图,把几个表的字段组合在一起,它的应用场景比如一个自定义协议有消息头和消息体,而两者是分开到两个 ByteBuf 的,那么这时候要怎么把两个ByteBuf 放到一起管理呢?compositeByteBuf就可以解决这个问题。
    

    源码

     compositeByteBuf 内部放着一个 Components 的数组,这个 Components 是什么呢?
    
        private final class Component {
            final ByteBuf buf;
            final int length;
            int offset;
            int endOffset;
    
            Component(ByteBuf buf) {
                this.buf = buf;
                length = buf.readableBytes();
            }
    
            void freeIfNecessary() {
                // Unwrap so that we can free slices, too.
                buf.release(); // We should not get a NPE here. If so, it must be a bug.
            }
        }
    
    
    可以看到实际就是 ByteBuf 的包装类,我们看一下它的使用
     addComponent 方法
    
        /**
         * Add the given {@link ByteBuf} on the specific index.
         *
         * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}.
         * If you need to have it increased you need to handle it by your own.
         *
         * @param cIndex the index on which the {@link ByteBuf} will be added
         * @param buffer the {@link ByteBuf} to add
         */
        public CompositeByteBuf addComponent(int cIndex, ByteBuf buffer) {
            addComponent0(cIndex, buffer);
            consolidateIfNeeded();
            return this;
        }
    
        private int addComponent0(int cIndex, ByteBuf buffer) {
            checkComponentIndex(cIndex);
    
            if (buffer == null) {
                throw new NullPointerException("buffer");
            }
    
            int readableBytes = buffer.readableBytes();
            if (readableBytes == 0) {
                return cIndex;
            }
    
            // No need to consolidate - just add a component to the list.
            Component c = new Component(buffer.order(ByteOrder.BIG_ENDIAN).slice());
            if (cIndex == components.size()) {
                components.add(c);
                if (cIndex == 0) {
                    c.endOffset = readableBytes;
                } else {
                    Component prev = components.get(cIndex - 1);
                    c.offset = prev.endOffset;
                    c.endOffset = c.offset + readableBytes;
                }
            } else {
                components.add(cIndex, c);
                updateComponentOffsets(cIndex);
            }
            return cIndex;
        }
    
    
    removeComponent 方法同理
    

    补充

     ByteBufUtil 这个类是可以对 ByteBuf进行操作。 
    

    ##参考资料

    • 《netty权威指南》
  • 相关阅读:
    java代码split分割数字类
    P1330 封锁阳光大学
    1022 舞会2
    1626 爱在心中
    P2024 食物链(two)
    P1196 银河英雄传说
    P1892 团伙
    P1546 最短网络(最小生成树)
    烦人的幻灯片(拓扑)
    例4.15 奖金(拓扑排序)
  • 原文地址:https://www.cnblogs.com/Benjious/p/11634910.html
Copyright © 2020-2023  润新知