Skip to content

Commit 096edff

Browse files
committed
Fix Java IterableByteBufferInputStream to return -1 on empty
This gives the InputStream slightly less work to do when it knows there are no buffers that can be checked for more data. Also loosened a check in CodedInputStream to permit read() to return zero, as this is documented as a valid value - though in this case -1 is the correct value as there is nothing more to read. Fixes #23957
1 parent 26d08d5 commit 096edff

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

java/core/src/main/java/com/google/protobuf/CodedInputStream.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2889,7 +2889,7 @@ private boolean tryRefillBuffer(int n) throws IOException {
28892889
buffer.length - bufferSize,
28902890
// do not exceed the total bytes limit
28912891
sizeLimit - totalBytesRetired - bufferSize));
2892-
if (bytesRead == 0 || bytesRead < -1 || bytesRead > buffer.length) {
2892+
if (bytesRead < -1 || bytesRead > buffer.length) {
28932893
throw new IllegalStateException(
28942894
input.getClass()
28952895
+ "#read(byte[]) returned invalid result: "

java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ final class IterableByteBufferInputStream extends InputStream {
6262

6363
if (!getNextByteBuffer()) {
6464
currentByteBuffer = EMPTY_BYTE_BUFFER;
65-
currentIndex = 0;
65+
currentIndex = dataSize;
6666
currentByteBufferPos = 0;
6767
currentAddress = 0;
6868
}

java/core/src/test/java/com/google/protobuf/IterableByteBufferInputStreamTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,19 @@ public void testEmptyBuffers() throws Exception {
3737
assertThat(in.read()).isEqualTo(-1);
3838
}
3939
}
40+
41+
@Test
42+
public void testAllEmpty() throws Exception {
43+
verifyEmpty();
44+
verifyEmpty(ByteBuffer.wrap(new byte[0]));
45+
verifyEmpty(ByteBuffer.wrap(new byte[0]),
46+
ByteBuffer.wrap(new byte[0]),
47+
ByteBuffer.wrap(new byte[0]));
48+
}
49+
50+
private static void verifyEmpty(ByteBuffer... buffers) throws Exception {
51+
try (InputStream in = new IterableByteBufferInputStream(Arrays.asList(buffers))) {
52+
assertThat(in.read()).isEqualTo(-1);
53+
}
54+
}
4055
}

0 commit comments

Comments
 (0)