ByteBufferList skip bug
Created by: frank-fan
There is a bug about ByteBufferList#skip.
ByteBufferList list = new ByteBufferList();
list.add(ByteBuffer.wrap("12345".getBytes()));
list.add(ByteBuffer.wrap("67890".getBytes()));
list.skip(3);
String content = list.readString();
System.out.println(content);
Above code should output "4567890" instead of "1234567890".
I checked skip(int) method, redirecting to get(null, 0, length), and found out why.
public void get(byte[] bytes, int offset, int length) {
if (remaining() < length)
throw new IllegalArgumentException("length");
int need = length;
while (need > 0) {
ByteBuffer b = mBuffers.peek();
int read = Math.min(b.remaining(), need);
if (bytes != null)
b.get(bytes, offset, read);
need -= read;
offset += read;
if (b.remaining() == 0) {
ByteBuffer removed = mBuffers.remove();
assert b == removed;
reclaim(b);
}
}
remaining -= length;
}
When bytes is null, non effect will be took to ByteBuffer b, position should be still without change. I changed the code described as below, and fix this.
public void get(byte[] bytes, int offset, int length) {
if (remaining() < length)
throw new IllegalArgumentException("length");
int need = length;
while (need > 0) {
ByteBuffer b = mBuffers.peek();
int read = Math.min(b.remaining(), need);
if (bytes != null) {
b.get(bytes, offset, read);
} else {
//when bytes is null, just skip data.
b.position(b.position() + read);
}
need -= read;
offset += read;
if (b.remaining() == 0) {
ByteBuffer removed = mBuffers.remove();
assert b == removed;
reclaim(b);
}
}
remaining -= length;
}