#include <assert.h>
#include <stdlib.h>
#include "array.h"


// construct an int array with size elements, zero them

IntArrayClass::IntArrayClass(int size)
{
   int i;

   assert (size >= 0);

   elems = size;
   ia = new int[elems];
   assert (ia != NULL);

   for (i = 0; i < elems; i++)
      ia[i] = 0;
}


// de-allocate an array

IntArrayClass::~IntArrayClass(void)
{
   delete [] ia;
}


// return number of elements in array

int IntArrayClass::size(void)
{
   return elems;
}


// return value of one element of the array

int IntArrayClass::read(int index)
{
   assert (0 <= index && index < elems);
   return ia[index];
}


// set value of one element of the array

void IntArrayClass::set(int index, int value)
{
   assert (0 <= index && index < elems);
   ia[index] = value;
}


// make the array larger or smaller
// making it smaller truncates elements from the end
// making it larger adds new 0 elements to the end

int IntArrayClass::resize(int newSize)
{
   int *ta;
   int i;
   int limit;

   assert (newSize >= 0);

   // allocate space for the new array, which may be larger *or* smaller
   // than the old array

   ta = new int[elems];
   assert (ta != NULL);

   // determine point at which to stop copying elements from old array
   // to new array

   limit = (elems < newSize) ? elems : newSize;

   for (i = 0; i < limit; i++)   // copy elements
      ta[i] = ia[i];

   // zero the enlarged part of the array, if necessary

   for ( ; i < newSize; i++)
      ta[i] = 0;

   delete [] ia;   // delete old array

   ia = ta;        // "remember" new array
   elems = newSize;
}
