public abstract class Buffer {
/**
* 标记
*/
private int mark = -1;
/**
* 位置,下一个要被读或写的元素的索引
*/
private int position = 0;
/**
* 上界,缓冲区的第一个不能被读或写的元素
*/
private int limit;
/**
* 容量,缓冲区能够容纳的数据元素的最大数量
*/
private int capacity;
public final boolean hasRemaining() {
return position < limit;
}
public final int remaining() {
return limit - position;
}
/**
* 将limit设置为当前position,然后将position重置为0,mark重置为-1
* 将一个能够继续添加数据元素的填充状态的缓冲区翻转成一个准备读出元素的释放状态
*/
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
/**
* 将position重置为0,mark重置为-1
* 重读已经被翻转的缓冲区中的数据
*/
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
/**
* 把position设回0,并将limit设为capacity的值
* 将缓冲区重置为空状态,并不改变缓冲区中的任何数据元素
*/
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
/**
* 将mark设为当前的position
*/
public final Buffer mark() {
mark = position;
return this;
}
/**
* 将position设为当前的mark
*/
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
}
static void checkBounds(int off, int len, int size) { // package-private
if ((off | len | (off + len) | (size - (off + len))) < 0)
throw new IndexOutOfBoundsException();
}
}
0 <= mark <= position <= limit <= capacity