Skip to content

Commit

Permalink
Fix #3477: javalib Channels.newChannel#read now reports EOF
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeTibbert committed Sep 13, 2023
1 parent 5d28d3e commit 56f8eda
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
15 changes: 11 additions & 4 deletions javalib/src/main/scala/java/nio/channels/Channels.scala
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,27 @@ object Channels {
new ReadableByteChannel {
var closed = false
override def read(dst: ByteBuffer): Int = synchronized {
if (closed) throw new ClosedChannelException()
if (closed)
throw new ClosedChannelException()

var eof = false
var written = 0
val capacity = dst.capacity()

while ({
val readByte = in.read()
if (readByte != -1) {
if (readByte == -1) {
eof = true
false
} else {
dst.put(readByte.toByte)
written += 1
capacity > written
} else false
}
}) ()

written
if ((written == 0) && eof) -1
else written
}
override def close(): Unit = synchronized {
in.close()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,23 @@ class ChannelsTest {
assertArrayEquals(expected, byteBuffer.array())
}

// Issue 3477
@Test def newChannelInputStreamReportsEOF(): Unit = {
val expected = Array[Byte](1, 2, 3)
val in = new ByteArrayInputStream(expected, 0, 3)
val channel = Channels.newChannel(in)

val byteBuffer = ByteBuffer.allocate(3)

// Read, check, and then discard expected in order to get to EOF
channel.read(byteBuffer)
assertArrayEquals(expected, byteBuffer.array())
byteBuffer.rewind()

val nRead = channel.read(byteBuffer)
assertEquals("Read of channel at EOF)", -1, nRead)
}

@Test def newChannelInputStreamThrows(): Unit = {
assumeFalse(
"Bug in the JVM, works for later versions than java 8",
Expand Down

0 comments on commit 56f8eda

Please sign in to comment.