Skip to content

Instantly share code, notes, and snippets.

@shawnz
Last active March 19, 2021 22:17
Show Gist options
  • Save shawnz/4b58bd9207eb0d8a03e66f0d9f42a82f to your computer and use it in GitHub Desktop.
Save shawnz/4b58bd9207eb0d8a03e66f0d9f42a82f to your computer and use it in GitHub Desktop.
package org.shawnz;
import java.io.IOException;
import java.io.InputStream;
public class TruncatedInputStream extends InputStream {
private final long maxLength;
private final InputStream underlying;
private long read;
public TruncatedInputStream(InputStream underlying, long maxLength) {
if (underlying == null)
throw new NullPointerException();
this.underlying = underlying;
if (maxLength < 0)
throw new IllegalArgumentException();
this.maxLength = maxLength;
}
public long getMaxLength() {
return maxLength;
}
public long getRead() {
return read;
}
@Override
public int available() throws IOException {
int underlyingAvailable = underlying.available();
if (maxLength - read > underlyingAvailable)
return underlyingAvailable;
if (maxLength - read > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) (maxLength - read);
}
@Override
public int read() throws IOException {
if (read >= maxLength)
return -1;
read++;
return underlying.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (read >= maxLength)
return -1;
if (len > b.length - off)
throw new IndexOutOfBoundsException();
int bytesToWrite = len;
if (bytesToWrite > maxLength - read)
bytesToWrite = (int) (maxLength - read);
int bytesWritten = underlying.read(b, off, bytesToWrite);
if (bytesWritten < 0)
return -1;
read += bytesWritten;
return bytesWritten;
}
@Override
public byte[] readNBytes(int len) throws IOException {
int bytesToWrite = len;
if (bytesToWrite > maxLength - read)
bytesToWrite = (int) (maxLength - read);
byte[] result = underlying.readNBytes(bytesToWrite);
read += result.length;
return result;
}
@Override
public long skip(long n) throws IOException {
long bytesToSkip = n;
if (bytesToSkip > maxLength - read)
bytesToSkip = maxLength - read;
long bytesSkipped = underlying.skip(bytesToSkip);
read += bytesSkipped;
return bytesSkipped;
}
@Override
public void close() throws IOException {
underlying.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment