Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #3477: javalib Channels.newChannel#read now reports EOF #3478

Merged
merged 2 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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