Skip to content

Commit

Permalink
ByteBuf#ensureWritable(int, boolean) should not throw
Browse files Browse the repository at this point in the history
Motivation:
The javadocs for ByteBuf#ensureWritable(int, boolean) indicate that it should not throw, and instead the return code should indicate the result of the operation. Due to a bug in AbstractByteBuf it is possible for a resize to be attempted on a buffer that may exceed maxCapacity() and therefore throw.

Modifications:
- If there is not enough space in the buffer, and force is false, then a resize should not be attempted

Result:
AbstractByteBuf#ensureWritable(int, boolean) enforces the javadoc constraints and does not throw.
  • Loading branch information
Scottmitch committed May 9, 2017
1 parent 1410899 commit 63f5cdb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
14 changes: 7 additions & 7 deletions buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java
Original file line number Diff line number Diff line change
Expand Up @@ -295,15 +295,15 @@ public int ensureWritable(int minWritableBytes, boolean force) {
return 0;
}

final int maxCapacity = maxCapacity();
final int writerIndex = writerIndex();
if (minWritableBytes > maxCapacity - writerIndex) {
if (force) {
if (capacity() == maxCapacity()) {
return 1;
}

capacity(maxCapacity());
return 3;
if (!force || capacity() == maxCapacity) {
return 1;
}

capacity(maxCapacity);
return 3;
}

// Normalize the current capacity to the power of 2.
Expand Down
17 changes: 17 additions & 0 deletions buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2471,6 +2471,23 @@ public void testNioBufferExposeOnlyRegion() {
buffer.release();
}

@Test
public void ensureWritableWithForceDoesNotThrow() {
ensureWritableDoesNotThrow(true);
}

@Test
public void ensureWritableWithOutForceDoesNotThrow() {
ensureWritableDoesNotThrow(false);
}

private void ensureWritableDoesNotThrow(boolean force) {
final ByteBuf buffer = newBuffer(8);
buffer.writerIndex(buffer.capacity());
buffer.ensureWritable(8, force);
buffer.release();
}

// See:
// - https://github.com/netty/netty/issues/2587
// - https://github.com/netty/netty/issues/2580
Expand Down

0 comments on commit 63f5cdb

Please sign in to comment.