diff --git a/runtime/src/main/java/org/capnproto/ArrayInputStream.java b/runtime/src/main/java/org/capnproto/ArrayInputStream.java index 3c9b321..bcadb28 100644 --- a/runtime/src/main/java/org/capnproto/ArrayInputStream.java +++ b/runtime/src/main/java/org/capnproto/ArrayInputStream.java @@ -36,6 +36,10 @@ public final class ArrayInputStream implements BufferedInputStream { public final int read(ByteBuffer dst) throws IOException { int available = this.buf.remaining(); int size = java.lang.Math.min(dst.remaining(), available); + if (size == 0) { + // end of stream + return -1; + } ByteBuffer slice = this.buf.slice(); slice.limit(size); diff --git a/runtime/src/test/scala/org/capnproto/ArrayInputStreamSuite.scala b/runtime/src/test/scala/org/capnproto/ArrayInputStreamSuite.scala index 6d8f195..18da8d9 100644 --- a/runtime/src/test/scala/org/capnproto/ArrayInputStreamSuite.scala +++ b/runtime/src/test/scala/org/capnproto/ArrayInputStreamSuite.scala @@ -29,6 +29,17 @@ class ArrayInputStreamSuite extends FunSuite { test("EmptyArray") { val stream = new ArrayInputStream(ByteBuffer.allocate(0)) 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 } }