diff --git a/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java b/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java index b9bad60bf4..b4e399b81d 100644 --- a/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java +++ b/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java @@ -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}. This is an expert method! + * + *

+ * Please note that since a {@link CompositeChannelBuffer} is made up of + * multiple {@link ChannelBuffer}s, this does not return the full buffer. + * Instead, it only returns a portion of the composite buffer where the + * index is located + *

+ * + * + * @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) { diff --git a/src/test/java/org/jboss/netty/buffer/AbstractCompositeChannelBufferTest.java b/src/test/java/org/jboss/netty/buffer/AbstractCompositeChannelBufferTest.java index e42032ecc9..7318dea648 100644 --- a/src/test/java/org/jboss/netty/buffer/AbstractCompositeChannelBufferTest.java +++ b/src/test/java/org/jboss/netty/buffer/AbstractCompositeChannelBufferTest.java @@ -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;