Skip to content

Commit

Permalink
Fix #3477: javalib Channels.newChannel#read now reports EOF (#3478)
Browse files Browse the repository at this point in the history
* Fix #3477: javalib Channels.newChannel#read now reports EOF

* Restart CI; no semantic changes
  • Loading branch information
LeeTibbert committed Sep 19, 2023
1 parent 7abb223 commit f50d68d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
17 changes: 13 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,25 +52,34 @@ 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()
closed = true
}

override def isOpen(): Boolean = synchronized { !closed }
}
}
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 f50d68d

Please sign in to comment.