From aa2f16f3143e46412e3c043b097e0f70f5026196 Mon Sep 17 00:00:00 2001 From: Bryce Anderson Date: Tue, 21 Mar 2017 10:14:13 -0700 Subject: [PATCH] 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. --- .../src/main/java/io/netty/buffer/EmptyByteBuf.java | 2 +- .../test/java/io/netty/buffer/EmptyByteBufTest.java | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/buffer/src/main/java/io/netty/buffer/EmptyByteBuf.java b/buffer/src/main/java/io/netty/buffer/EmptyByteBuf.java index 07dc18c269..ebe3b45391 100644 --- a/buffer/src/main/java/io/netty/buffer/EmptyByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/EmptyByteBuf.java @@ -760,7 +760,7 @@ public final class EmptyByteBuf extends ByteBuf { @Override public ByteBuf writeBytes(ByteBuf src) { - throw new IndexOutOfBoundsException(); + return checkLength(src.readableBytes()); } @Override diff --git a/buffer/src/test/java/io/netty/buffer/EmptyByteBufTest.java b/buffer/src/test/java/io/netty/buffer/EmptyByteBufTest.java index dd8697ecb5..6a31b51e00 100644 --- a/buffer/src/test/java/io/netty/buffer/EmptyByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/EmptyByteBufTest.java @@ -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);