package io;

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

/**
 * This decorated input stream is capable of reading fixed number of bytes.
 * In case that underlying input stream ends before required number of bytes has
 * been read, zero bytes are returned. If maximum number of bytes allowed has
 * been read, this stream will start to indicate end of stream even when
 * underlying stream is not yet at the end.
 * 
 * @author Marcel Duris
 * @see  InputStream
 */
public class PaddingInputStream extends InputStream {

    InputStream in;
    long fragmentSize;
    long pos;

    /**
     * Constructor that will create decorated input stream.
     * 
     * @param in input stream to be decorated
     * @param fragmentSize number of bytes expected to be read
     */
    public PaddingInputStream(InputStream in, long fragmentSize) {
        this.in = in;
        this.fragmentSize = fragmentSize;
        pos = 0;
    }

    /**
     * Overrided method that guarantees desired properties of stream.
     * 
     * @return single byte of file or -1 if stream has reached its end
     * @throws IOException if decorated input stream encounters error on read
     */
    @Override
    public int read() throws IOException {

        if (pos++ < fragmentSize) {
            int r = in.read();
            if (r < 0) {
                return 0;
            } else {
                return r;
            }
        } else {
            return -1;
        }
    }
}
