package jp.sourceforge.nicoro;

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

public class PartialInputStream extends InputStream {
	
	private InputStream mSource;
	private int mSize;
	private int mReaded;
	
	/**
	 * 
	 * @param source 読み込み元のInputStream
	 * @param size 読み込むサイズ
	 */
	public PartialInputStream(InputStream source, int size) {
		mSource = source;
		mSize = size;
		mReaded = 0;
	}

	@Override
    public int available() throws IOException {
        return Math.min(mSource.available(), mSize - mReaded);
    }
	
	/**
	 * ラッピング対象のInputStreamの自動close()は行わない
	 */
	@Override
    public void close() {
        // 何もしない
    }
	
	@Override
	public int read() throws IOException {
		if (mReaded >= mSize) {
			return -1;
		}
	
		int ret = mSource.read();
		if (ret >= 0) {
			++mReaded;
			assert mReaded <= mSize;
		}
		return ret;
	}

	@Override
    public int read(byte[] b, int offset, int length) throws IOException {
		if (mReaded >= mSize) {
			return -1;
		}
	
		int ret = mSource.read(b, offset, Math.min(length, mSize - mReaded));
		if (ret >= 0) {
			mReaded += ret;
			assert mReaded <= mSize;
		}
		return ret;
	}
	
	@Override
    public long skip(long n) throws IOException {
        if (n <= 0) {
            return 0;
        }
		if (mReaded >= mSize) {
			return 0L;
		}
	
		long ret = mSource.skip(Math.min(n, mSize - mReaded));
		if (ret >= 0) {
			mReaded += ret;
			assert mReaded <= mSize;
		}
		return ret;
    }
}
