ArrayInputStream: return -1 on end-of-stream

This commit is contained in:
David Renshaw 2018-06-10 13:25:40 -04:00
parent edcbf1f61c
commit 6dcfa30e10
2 changed files with 16 additions and 1 deletions

View file

@ -36,6 +36,10 @@ public final class ArrayInputStream implements BufferedInputStream {
public final int read(ByteBuffer dst) throws IOException { public final int read(ByteBuffer dst) throws IOException {
int available = this.buf.remaining(); int available = this.buf.remaining();
int size = java.lang.Math.min(dst.remaining(), available); int size = java.lang.Math.min(dst.remaining(), available);
if (size == 0) {
// end of stream
return -1;
}
ByteBuffer slice = this.buf.slice(); ByteBuffer slice = this.buf.slice();
slice.limit(size); slice.limit(size);

View file

@ -29,6 +29,17 @@ class ArrayInputStreamSuite extends FunSuite {
test("EmptyArray") { test("EmptyArray") {
val stream = new ArrayInputStream(ByteBuffer.allocate(0)) val stream = new ArrayInputStream(ByteBuffer.allocate(0))
val dst = ByteBuffer.allocate(10) val dst = ByteBuffer.allocate(10)
stream.read(dst) should equal (0)
// read() should return -1 at the end of the stream
// https://docs.oracle.com/javase/7/docs/api/java/nio/channels/ReadableByteChannel.html
stream.read(dst) should equal (-1)
}
test("Request more bytes than are present") {
val oneByte: Array[Byte] = Array(42)
val stream = new ArrayInputStream(ByteBuffer.wrap(oneByte))
val dst = ByteBuffer.allocate(10)
stream.read(dst) should equal (1)
stream.read(dst) should equal (-1) // end of stream
} }
} }