Skip to content

Instantly share code, notes, and snippets.

@ncruces
Last active May 21, 2018 02:01
Show Gist options
  • Save ncruces/e662c3888aca1054ef54f64d1bb7dd17 to your computer and use it in GitHub Desktop.
Save ncruces/e662c3888aca1054ef54f64d1bb7dd17 to your computer and use it in GitHub Desktop.
InputStream that reads at most N bytes from underlying stream
package io.github.ncruces.utils;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.Math.min;
public class BoundedInputStream extends InputStream {
private final InputStream in;
private final long max;
private long pos;
private long mark;
public BoundedInputStream(InputStream in, long max) {
if (in == null) throw new NullPointerException();
if (max < 0) throw new IllegalArgumentException();
this.in = in;
this.max = max;
}
@Override
public int read() throws IOException {
if (pos >= max) return -1;
int read = in.read();
if (read >= 0) ++pos;
else pos = max;
return read;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) return 0;
if (pos >= max) return -1;
int read = in.read(b, off, (int)min(len, max - pos));
if (read >= 0) pos += read;
else pos = max;
return read;
}
@Override
public long skip(long n) throws IOException {
long skipped = in.skip(min(n, max - pos));
pos += skipped;
return skipped;
}
@Override
public int available() throws IOException {
return (int)min(in.available(), max - pos);
}
@Override
public boolean markSupported() {
return in.markSupported();
}
@Override
public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = pos;
}
@Override
public synchronized void reset() throws IOException {
in.reset();
pos = mark;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment