|
| 1 | +package life.qbic.application.commons; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | +import java.nio.ByteBuffer; |
| 6 | +import java.util.Iterator; |
| 7 | +import java.util.Objects; |
| 8 | + |
| 9 | +/** |
| 10 | + * An input stream generated from a (lazy) iterator of {@link ByteBuffer}s. |
| 11 | + */ |
| 12 | +public class ByteBufferIteratorInputStream extends InputStream { |
| 13 | + |
| 14 | + private final Iterator<ByteBuffer> bufferIterator; |
| 15 | + private ByteBuffer currentBuffer; |
| 16 | + |
| 17 | + public ByteBufferIteratorInputStream(Iterator<ByteBuffer> iterator) { |
| 18 | + this.bufferIterator = iterator; |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public int read(byte[] b, int off, int len) throws IOException { |
| 23 | + Objects.checkFromIndexSize(off, len, b.length); |
| 24 | + if (len == 0) { |
| 25 | + return 0; |
| 26 | + } |
| 27 | + boolean bufferAvailable = makeBufferAvailable(); |
| 28 | + if (!bufferAvailable) { |
| 29 | + return -1; |
| 30 | + } |
| 31 | + |
| 32 | + int requestedBytes = Math.min(currentBuffer.remaining(), len); |
| 33 | + currentBuffer.get(currentBuffer.position(), b, off, requestedBytes); |
| 34 | + currentBuffer.position(currentBuffer.position() + requestedBytes); |
| 35 | + |
| 36 | + return requestedBytes; |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public int read() { |
| 41 | + boolean bufferAvailable = makeBufferAvailable(); |
| 42 | + if (!bufferAvailable) { |
| 43 | + return -1; |
| 44 | + } |
| 45 | + var currentPosition = currentBuffer.position(); |
| 46 | + var value = currentBuffer.get(currentPosition) & 0xFF; |
| 47 | + currentBuffer.position(currentPosition + 1); |
| 48 | + return value; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Ensures a readable buffer is set. |
| 53 | + * |
| 54 | + * @return true if a readable buffer is selected; false if no readable buffer is available. |
| 55 | + */ |
| 56 | + private boolean makeBufferAvailable() { |
| 57 | + var buffer = currentBuffer; |
| 58 | + if (buffer != null && !buffer.hasRemaining()) { |
| 59 | + // the current buffer is read completely |
| 60 | + buffer = null; |
| 61 | + } |
| 62 | + while (buffer == null) { |
| 63 | + if (!bufferIterator.hasNext()) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + buffer = bufferIterator.next(); |
| 67 | + } |
| 68 | + currentBuffer = buffer; |
| 69 | + return true; |
| 70 | + } |
| 71 | +} |
0 commit comments