TerminatedInputStream.java

/*
 * Copyright (c) 2020, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.io.sub;

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

/**
 * A wrapping input stream that terminates the input when the terminating
 * byte is read. Closing this stream does not close the underlying stream;
 * instead it reads and discards bytes up to and including the terminating
 * byte, leaving the underlying stream positioned for the next read.
 */
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;
    }
}