Backport getBuffer(..) method in CompositeChannelBuffer. See #414 and #415

This commit is contained in:
Norman Maurer 2012-06-29 13:04:15 +02:00
parent 31ca517627
commit 076a6a9239
2 changed files with 48 additions and 0 deletions

View File

@ -559,6 +559,35 @@ public class CompositeChannelBuffer extends AbstractChannelBuffer {
dst.writerIndex(dst.capacity());
}
/**
* Returns the {@link ChannelBuffer} portion of this {@link CompositeChannelBuffer} that
* contains the specified {@code index}. <strong>This is an expert method!</strong>
*
* <p>
* Please note that since a {@link CompositeChannelBuffer} is made up of
* multiple {@link ChannelBuffer}s, this does <em>not</em> return the full buffer.
* Instead, it only returns a portion of the composite buffer where the
* index is located
* </p>
*
*
* @param index The {@code index} to search for and include in the returned {@link ByteBuf}
* @return The {@link ByteBuf} that contains the specified {@code index}
* @throws IndexOutOfBoundsException when the specified {@code index} is
* less than zero, or larger than {@code capacity()}
*/
public ChannelBuffer getBuffer(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= capacity()) {
throw new IndexOutOfBoundsException("Invalid index: " + index
+ " - Bytes needed: " + index + ", maximum is "
+ capacity());
}
//Return the component byte buffer
return components[componentId(index)];
}
public ChannelBuffer slice(int index, int length) {
if (index == 0) {
if (length == 0) {

View File

@ -90,6 +90,25 @@ public abstract class AbstractCompositeChannelBufferTest extends
return false;
}
@Test
public void testGetBuffer() {
CompositeChannelBuffer buf = (CompositeChannelBuffer) ChannelBuffers.wrappedBuffer(new byte[] { 1, 2, 3, 4, 5 }, new byte[] {4, 5, 6, 7, 8, 9, 26});
//Ensure that a random place will be fine
assertEquals(buf.getBuffer(2).capacity(), 5);
//Loop through each byte
byte index = 0;
while (index < buf.capacity()) {
ChannelBuffer _buf = buf.getBuffer(index++);
assertNotNull(_buf);
assertTrue(_buf.capacity() > 0);
assertNotNull(_buf.getByte(0));
assertNotNull(_buf.getByte(_buf.readableBytes() - 1));
}
}
@Test
public void testDiscardReadBytes3() {
ChannelBuffer a, b;