Skip to content

Instantly share code, notes, and snippets.

@shawnz
Last active March 19, 2021 22:34
Show Gist options
  • Save shawnz/905274b7e4d1016c9433a0f3de5e5351 to your computer and use it in GitHub Desktop.
Save shawnz/905274b7e4d1016c9433a0f3de5e5351 to your computer and use it in GitHub Desktop.
package org.shawnz;
import java.io.InputStream;
import java.util.Arrays;
public class ZeroInputStream extends InputStream {
private final long zeroes;
private long read;
public ZeroInputStream() {
this.zeroes = -1;
}
public ZeroInputStream(long zeroes) {
if (zeroes < -1)
throw new IllegalArgumentException();
this.zeroes = zeroes;
}
public long getZeroes() {
return zeroes;
}
public long getRead() {
return read;
}
@Override
public int available() {
if (zeroes < 0)
return 0;
if (zeroes - read > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) (zeroes - read);
}
@Override
public int read() {
if (zeroes >= 0 && read >= zeroes)
return -1;
read++;
return 0;
}
@Override
public int read(byte[] b, int off, int len) {
if (zeroes >= 0 && read >= zeroes)
return -1;
if (off < 0 || len < 0 || len > b.length - off)
throw new IndexOutOfBoundsException();
int bytesToWrite = len;
if (zeroes >= 0 && bytesToWrite > zeroes - read)
bytesToWrite = (int) (zeroes - read);
Arrays.fill(b, off, off + bytesToWrite, (byte) 0);
read += bytesToWrite;
return bytesToWrite;
}
@Override
public byte[] readNBytes(int len) {
int bytesToWrite = len;
if (zeroes >= 0 && bytesToWrite > zeroes - read)
bytesToWrite = (int) (zeroes - read);
read += bytesToWrite;
return new byte[bytesToWrite];
}
@Override
public long skip(long n) {
long bytesToSkip = n;
if (zeroes >= 0 && bytesToSkip > zeroes - read)
bytesToSkip = zeroes - read;
read += bytesToSkip;
return bytesToSkip;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment