From c8db4354c3abbe8872877029a96417235aca6a47 Mon Sep 17 00:00:00 2001 From: danf Date: Wed, 17 Jan 2018 15:09:02 +0200 Subject: [PATCH] Fix #129 - fill buffer completely in read before calling consumers. --- .../redline_rpm/ReadableChannelWrapper.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/redline_rpm/ReadableChannelWrapper.java b/src/main/java/org/redline_rpm/ReadableChannelWrapper.java index 6253fc4..9047fed 100644 --- a/src/main/java/org/redline_rpm/ReadableChannelWrapper.java +++ b/src/main/java/org/redline_rpm/ReadableChannelWrapper.java @@ -1,6 +1,7 @@ package org.redline_rpm; import java.io.IOException; +import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; @@ -23,19 +24,28 @@ public ReadableChannelWrapper( final ReadableByteChannel channel) { * * @param buffer the buffer to read into * @return the number of bytes read from the underlying channel - * @throws IOException if an IO error occurrs + * @throws IOException if an IO error occurs */ public int read( final ByteBuffer buffer) throws IOException { - final int read = channel.read( buffer); - for ( Consumer< ?> consumer : consumers.values()) consumer.consume(( ByteBuffer) buffer.duplicate().flip()); - return read; + int total = 0; + while (buffer.hasRemaining()) { + int read; + if ((read = channel.read(buffer)) == -1) { + throw new BufferUnderflowException(); + } + total += read; + } + for (Consumer consumer : consumers.values()) { + consumer.consume(( ByteBuffer) buffer.duplicate().flip()); + } + return total; } /** * Close the underlying read channel and complete any operations in the * consumer. * - * @throws IOException if an IO error occurrs + * @throws IOException if an IO error occurs */ public void close() throws IOException { channel.close();