package jp.sourceforge.nicoro;

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

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

	@Override
    public int available() throws IOException {
        return mSize - mReaded;
    }
	
	/**
	 * ラッピング対象のRandomAccessFileの自動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;
		}
	
		int ret = mSource.skipBytes((int) Math.min(n, mSize - mReaded));
		if (ret >= 0) {
			mReaded += ret;
			assert mReaded <= mSize;
		}
		return ret;
    }
}
