TerminatedInputStream.java

package net.morimekta.io.sub;

import java.io.IOException;
import java.io.InputStream;

/**
 * A wrapping input stream that terminated the input whenever the
 * terminating byte is read. Will not close the enclosed stream
 * on close, and will try to read fully to the terminating byte
 * when closed if not already seen.
 */
public class TerminatedInputStream extends InputStream {
    private InputStream in;
    private final int terminator;

    public TerminatedInputStream(InputStream in) {
        this(in, 0);
    }

    public TerminatedInputStream(InputStream in, int terminator) {
        this.in = in;
        this.terminator = terminator;
    }

    @Override
    public int read() throws IOException {
        if (in == null) {
            return -1;
        }
        int b = in.read();
        if (b < 0 || b == terminator) {
            in = null;
            return -1;
        }
        return b;
    }

    @Override
    public void close() throws IOException {
        if (in != null) {
            int b;
            while ((b = in.read()) >= 0) {
                if (b == terminator) break;
            }
            in = null;
        }
    }

    @Override
    public int available() throws IOException {
        if (in == null) {
            return 0;
        }
        return in.available() > 0 ? 1 : 0;
    }
}