Last active
May 21, 2018 02:03
-
-
Save ncruces/da984d7d024eeeb5597ad81c7ac7683a to your computer and use it in GitHub Desktop.
InputStream that reads from a ByteBuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.ncruces.utils; | |
import java.io.InputStream; | |
import java.nio.ByteBuffer; | |
public final class ByteBufferInputStream extends InputStream { | |
private final ByteBuffer buf; | |
public ByteBufferInputStream(ByteBuffer buffer) { | |
if (buffer == null) throw new NullPointerException(); | |
buf = buffer; | |
} | |
@Override | |
public synchronized int read() { | |
if (buf.hasRemaining()) return buf.get() & 0xff; | |
return -1; | |
} | |
@Override | |
public synchronized int read(byte b[]) { | |
return read(0, b.length, b); | |
} | |
@Override | |
public synchronized int read(byte b[], int off, int len) { | |
if ((off | len | off + len | b.length - (off + len)) < 0) { | |
throw new IndexOutOfBoundsException(); | |
} | |
return read(off, len, b); | |
} | |
private int read(int off, int len, byte[] b) { | |
if (len == 0) return 0; | |
int rem = buf.remaining(); | |
if (rem <= 0) return -1; | |
if (rem > len) rem = len; | |
buf.get(b, off, rem); | |
return rem; | |
} | |
@Override | |
public synchronized long skip(long n) { | |
if (n <= 0) return 0; | |
int rem = buf.remaining(); | |
if (n > rem) n = rem; | |
buf.position((int)(buf.position() + n)); | |
return n; | |
} | |
@Override | |
public synchronized int available() { return buf.remaining(); } | |
@Override | |
public synchronized void mark(int readAheadLimit) { buf.mark(); } | |
@Override | |
public synchronized void reset() { buf.reset(); } | |
@Override | |
public boolean markSupported() { return true; } | |
@Override | |
public void close() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment