/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.collection.lists;

import java.util.RandomAccess;
import net.ranides.assira.collection.IntCollection;
import net.ranides.assira.collection.arrays.ArrayUtils;

/**
 * That implementation stores internally as small array as possible. It reallocates
 * memory after every operation. Empty list does not allocate any memory. 
 * Especially helpful for rarely modified collections with small number of elements,
 * or no elements at all.
 * 
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public class IntRTList extends AIntList implements RandomAccess {

    private final static int[] EMPTY = new int[0];
	
    private int[] content;

    public IntRTList() {
        content = EMPTY;
    }

    public IntRTList(IntCollection values) {
        content = values.toIntArray();
    }
	
	public IntRTList(int[] values) {
        content = ArrayUtils.copy(values);
    }

    @Override
    public int getInt(int index) {
        return content[index];
    }

    @Override
    public int size() {
        return content.length;
    }

    @Override
    public void clear() {
        content = EMPTY;
    }

    @Override
    public int set(int index, int element) {
        int prev = content[index];
        content[index] = element;
        return prev;
    }

    @Override
    public void add(int index, int element) {
        if(index > content.length) {
            throw new IndexOutOfBoundsException(index + " out of bound " + content.length);
        }
        if(content == EMPTY) {
            content = new int[]{ element };
            return;
        }
        int[] buffer = new int[content.length + 1];
        if(index > 0) {
            System.arraycopy(content, 0, buffer, 0, index);
        }
        if(index < content.length) {
            System.arraycopy(content, index, buffer, index+1, content.length - index);
        }
        buffer[index] = element;
        content = buffer;
    }

    @Override
    public int removeInt(int index) {
        if(index > content.length) {
            throw new IndexOutOfBoundsException(index + " out of bound " + content.length);
        }
        int prev = content[index];
        if(content.length == 1) {
            content = EMPTY;
            return prev;
        }
        int[] buffer = new int[content.length - 1];
        if(index > 0) {
            System.arraycopy(content, 0, buffer, 0, index);
        }
        if( content.length - index > 1) {
            System.arraycopy(content, index+1, buffer, index, content.length - index - 1);
        }

        content = buffer;
        return prev;
    }
	
	@Override
	public IntList subList(int begin, int end) {
		return IntListUtils.sublist(this, begin, end);
	}

}
