Skip to content

Commit b71b05a

Browse files
committed
Use ChannelBufferInput when FileInputStream is passed to the unpacker
1 parent 60f3a13 commit b71b05a

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

msgpack-core/src/main/java/org/msgpack/core/buffer/ChannelBufferInput.java

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,53 @@
44
import java.nio.ByteBuffer;
55
import java.nio.channels.ReadableByteChannel;
66

7-
import static org.msgpack.core.Preconditions.checkNotNull;
7+
import static org.msgpack.core.Preconditions.*;
88

99
/**
1010
* {@link MessageBufferInput} adapter for {@link java.nio.channels.ReadableByteChannel}
1111
*/
1212
public class ChannelBufferInput implements MessageBufferInput {
1313

1414
private final ReadableByteChannel channel;
15+
private boolean reachedEOF = false;
16+
private final int bufferSize;
1517

1618
public ChannelBufferInput(ReadableByteChannel channel) {
19+
this(channel, 8192);
20+
}
21+
22+
public ChannelBufferInput(ReadableByteChannel channel, int bufferSize) {
1723
this.channel = checkNotNull(channel, "input channel is null");
24+
checkArgument(bufferSize > 0, "buffer size must be > 0: " + bufferSize);
25+
this.bufferSize = bufferSize;
1826
}
1927

2028
@Override
2129
public MessageBuffer next() throws IOException {
22-
MessageBuffer m = MessageBuffer.newBuffer(8192);
30+
31+
if(reachedEOF)
32+
return null;
33+
34+
MessageBuffer m = MessageBuffer.newBuffer(bufferSize);
2335
ByteBuffer b = m.toByteBuffer(0, m.size);
24-
for(int ret = 0; (ret = channel.read(b)) != -1; ) {
36+
while(b.remaining() > 0) {
37+
int ret = 0;
38+
ret = channel.read(b);
39+
if(ret == -1) {
40+
reachedEOF = true;
41+
break;
42+
}
2543
}
2644
b.flip();
27-
if(b.remaining() < m.size)
28-
return m.slice(0, b.remaining());
29-
else
45+
if(b.remaining() == 0) {
46+
return null;
47+
}
48+
else if(b.limit() < m.size) {
49+
return m.slice(0, b.limit());
50+
}
51+
else {
3052
return m;
53+
}
3154
}
3255

3356
@Override

msgpack-core/src/main/java/org/msgpack/core/buffer/InputStreamBufferInput.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.msgpack.core.buffer;
22

33
import java.io.ByteArrayInputStream;
4+
import java.io.FileInputStream;
45
import java.io.IOException;
56
import java.io.InputStream;
67
import java.lang.reflect.Field;
@@ -50,6 +51,8 @@ public static MessageBufferInput newBufferInput(InputStream in) {
5051
catch(Exception e) {
5152
// Failed to retrieve the raw byte array
5253
}
54+
} else if (in instanceof FileInputStream) {
55+
return new ChannelBufferInput(((FileInputStream) in).getChannel());
5356
}
5457

5558
return new InputStreamBufferInput(in);

0 commit comments

Comments
 (0)