| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package org.jpype.pickle; |
| 17 |
|
| 18 |
import java.io.IOException; |
| 19 |
import java.io.InputStream; |
| 20 |
import java.nio.ByteBuffer; |
| 21 |
import java.util.LinkedList; |
| 22 |
|
| 23 |
public class ByteBufferInputStream extends InputStream |
| 24 |
{ |
| 25 |
|
| 26 |
private LinkedList<ByteBuffer> buffers = new LinkedList<>(); |
| 27 |
|
| 28 |
public void put(byte[] bytes) |
| 29 |
{ |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
ByteBuffer buffer = ByteBuffer.wrap(bytes); |
| 34 |
buffers.add(buffer); |
| 35 |
} |
| 36 |
|
| 37 |
@Override |
| 38 |
public int read() throws IOException |
| 39 |
{ |
| 40 |
if (buffers.isEmpty()) |
| 41 |
return -1; |
| 42 |
|
| 43 |
ByteBuffer b = buffers.getFirst(); |
| 44 |
while (b.remaining() == 0) |
| 45 |
{ |
| 46 |
buffers.removeFirst(); |
| 47 |
if (buffers.isEmpty()) |
| 48 |
return -1; |
| 49 |
b = buffers.getFirst(); |
| 50 |
} |
| 51 |
return b.get() & 0xFF; |
| 52 |
} |
| 53 |
|
| 54 |
@Override |
| 55 |
public int read(byte[] arg0) throws IOException |
| 56 |
{ |
| 57 |
return read(arg0, 0, arg0.length); |
| 58 |
} |
| 59 |
|
| 60 |
@Override |
| 61 |
public int read(byte[] buffer, int offset, int len) throws IOException |
| 62 |
{ |
| 63 |
if (buffer == null) |
| 64 |
throw new NullPointerException("Buffer cannot be null"); |
| 65 |
if (offset < 0 || len < 0 || len > buffer.length - offset) |
| 66 |
throw new IndexOutOfBoundsException("Invalid offset/length parameters"); |
| 67 |
if (len == 0) |
| 68 |
return 0; |
| 69 |
|
| 70 |
int total = 0; |
| 71 |
while (len > 0 && !buffers.isEmpty()) |
| 72 |
{ |
| 73 |
ByteBuffer b = buffers.getFirst(); |
| 74 |
int remaining = b.remaining(); |
| 75 |
if (remaining == 0) |
| 76 |
{ |
| 77 |
buffers.removeFirst(); |
| 78 |
continue; |
| 79 |
} |
| 80 |
|
| 81 |
int toRead = Math.min(len, remaining); |
| 82 |
b.get(buffer, offset, toRead); |
| 83 |
total += toRead; |
| 84 |
len -= toRead; |
| 85 |
offset += toRead; |
| 86 |
} |
| 87 |
return (total == 0) ? -1 : total; |
| 88 |
} |
| 89 |
|
| 90 |
@Override |
| 91 |
public void close() throws IOException |
| 92 |
{ |
| 93 |
buffers.clear(); |
| 94 |
} |
| 95 |
} |