121212212

1212121212


Segment

要想搞明白 okio 的运作机制,Segment 是首先要弄清楚的,Segment 是用作 okio包下的 Buffer 和 SegmentPool 的结点。

参数说明

    final class Segment {
        /** The size of all segments in bytes. */
        static final int SIZE = 2048;

        // 底层字节数组
        final byte[] data;

        /** The next byte of application data byte to read in this segment. */
        int pos;

        /** The first byte of available data ready to be written to. */
        int limit;

        /** True if other segments or byte strings use the same byte array. */
        boolean shared;

        /** True if this segment owns the byte array and can append to it, extending {@code limit}. */
        boolean owner;

        /** Next segment in a linked or circularly-linked list. */
        Segment next;

        /** Previous segment in a circularly-linked list. */
        Segment prev;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. byte[] data 很明显代表底层字节数组,用来存储字节。
  2. int pos 代表从这个 Segment 读取时候的起始位置
  3. int limit 代表向这个 Segment 写数据时候的起始位置
  4. boolean shared 代表当前 Segment 是否是共享的。如何决定共享呢?

    • 如果使用不带参数的构造函数创建,那么底层数组就是自己创建的,创建出来的 Segment 就是不共享的。

          Segment() {
              this.data = new byte[SIZE];
              this.owner = true;
              this.shared = false;
          }
      • 1
      • 2
      • 3
      • 4
      • 5
    • 如果使用另外一个 Segment 当作参数来创建新的 Segment,那么这这两个 Segment 都是共享的,共享的就是底层数组

          Segment(Segment shareFrom) {
              this(shareFrom.data, shareFrom.pos, shareFrom.limit);
              shareFrom.shared = true;
          }
      
          Segment(byte[] data, int pos, int limit) {
              this.data = data;
              this.pos = pos;
              this.limit = limit;
              this.owner = false;
              this.shared = true;
          }
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
  5. boolean owner 代表当前 Segment 是否是底层数组的拥有者。底层数组的第一个创建者就是拥有者,也就是调用无参构造方法创建的才是底层数组的拥有者。

猜你喜欢

转载自blog.csdn.net/xiongjiamu/article/details/80394670