EmptyByteBuf allows writing ByteBufs with 0 readable bytes

Motivation:

The contract of `ByteBuf.writeBytes(ByteBuf src)` is such that it will
throw an `IndexOutOfBoundsException if `src.readableBytes()` is greater than
`this.writableBytes()`. The EmptyByteBuf class will throw the exception,
even if the source buffer has zero readable bytes, in violation of the
contract.

Modifications:

Use the helper method `checkLength(..)` to check the length and throw
the exception, if appropriate.

Result:

Conformance with the stated behavior of ByteBuf.
This commit is contained in:
Bryce Anderson 2017-03-21 10:14:13 -07:00 committed by Norman Maurer
parent 9c1a191696
commit aa2f16f314
2 changed files with 14 additions and 1 deletions

View File

@ -760,7 +760,7 @@ public final class EmptyByteBuf extends ByteBuf {
@Override
public ByteBuf writeBytes(ByteBuf src) {
throw new IndexOutOfBoundsException();
return checkLength(src.readableBytes());
}
@Override

View File

@ -28,6 +28,19 @@ public class EmptyByteBufTest {
assertFalse(empty.isWritable(1));
}
@Test
public void testWriteEmptyByteBuf() {
EmptyByteBuf empty = new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT);
empty.writeBytes(Unpooled.EMPTY_BUFFER); // Ok
ByteBuf nonEmpty = UnpooledByteBufAllocator.DEFAULT.buffer().writeBoolean(false);
try {
empty.writeBytes(nonEmpty);
fail();
} catch (IndexOutOfBoundsException ignored) {
// Ignore.
}
}
@Test
public void testIsReadable() {
EmptyByteBuf empty = new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT);