Fixed a bug: NETTY-329 ChannelBuffer.slice(index, length) returns a slice with wrong reader/writerIndex

* HeapChannelBuffer.slice(index, length) and ByteBufferBackedChannelBuffer.slice(index, length) should update indexes when they created a slice using duplicate()
* Added relevant test cases
This commit is contained in:
Trustin Lee 2010-06-21 07:00:03 +00:00
parent 575b7fb073
commit f88108e876
3 changed files with 23 additions and 3 deletions

View File

@ -304,7 +304,9 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer {
public ChannelBuffer slice(int index, int length) {
if (index == 0 && length == capacity()) {
return duplicate();
ChannelBuffer slice = duplicate();
slice.setIndex(0, length);
return slice;
} else {
if (index >= 0 && length == 0) {
return ChannelBuffers.EMPTY_BUFFER;

View File

@ -192,7 +192,9 @@ public abstract class HeapChannelBuffer extends AbstractChannelBuffer {
return ChannelBuffers.EMPTY_BUFFER;
}
if (length == array.length) {
return duplicate();
ChannelBuffer slice = duplicate();
slice.setIndex(0, length);
return slice;
} else {
return new TruncatedChannelBuffer(this, length);
}

View File

@ -1472,8 +1472,24 @@ public abstract class AbstractChannelBufferTest {
}
@Test
public void testSlice() throws Exception {
public void testSliceEndianness() throws Exception {
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity()).order());
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 2).order());
}
@Test
public void testSliceIndex() throws Exception {
assertEquals(0, buffer.slice(0, buffer.capacity()).readerIndex());
assertEquals(0, buffer.slice(0, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 2).readerIndex());
assertEquals(buffer.capacity(), buffer.slice(0, buffer.capacity()).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(0, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(1, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 2, buffer.slice(1, buffer.capacity() - 2).writerIndex());
}
@Test