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;

    /**
     * Create default terminated input stream, terminating on '00' byte.
     *
     * @param in Stream to detect termination byte on.
     */
    public TerminatedInputStream(InputStream in) {
        this(in, 0);
    }

    /**
     * Create terminated input stream with specified terminator byte.
     *
     * @param in         Stream to detect termination byte on.
     * @param terminator Terminator byte.
     */
    public TerminatedInputStream(InputStream in, int terminator) {
        if (terminator < 0 || terminator > 255) {
            throw new IllegalArgumentException("Invalid terminator byte: " + 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;
    }
}