#include <cstring>
#include "section5b_fixed.h"

IntArrayList::IntArrayList()
  : cap_(10), size_(0) {
  arr_ = new int[cap_];
}
IntArrayList::IntArrayList(const IntArrayList& rhs)
  : cap_(rhs.cap_), size_(rhs.size_) {
  arr_ = new int[cap_];
  memcpy(arr_, rhs.arr_, size_ * sizeof(int));
}
IntArrayList::IntArrayList(const int* const arr, size_t size)
  : cap_((size + 1) * 2), size_(size) {
  arr_ = new int[cap_];
  memcpy(arr_, arr, size * sizeof(int));
}
IntArrayList::IntArrayList(size_t size)
  : cap_((size + 1) * 2), size_(size) {
  arr_ = new int[cap_];
}
IntArrayList::~IntArrayList() {
  delete [] arr_;
}


IntArrayList& IntArrayList::operator=(const IntArrayList& rhs)
{
  if (this != &rhs) {
    if (rhs.size_ > cap_) {
      delete [] arr_;
      arr_ = new int[rhs.cap_];
      cap_ = rhs.cap_;
    }
    size_ = rhs.size_;
    memcpy(arr_, rhs.arr_, size_ * sizeof(int));
  }
  return *this;
}
int& IntArrayList::operator[](size_t indx) {
  if (indx >= size_) {
    throw;
  }
  return arr_[indx];
}
IntArrayList& IntArrayList::operator+=(size_t n) {
  if (size_ == cap_) {
    cap_ = (cap_ + 1) * 2;
    int* tmp = new int[cap_];
    memcpy(tmp, arr_, size_ * sizeof(int));
    delete [] arr_;
    arr_ = tmp;
  }
  arr_[size_] = n;
  size_++;
  return *this;
}


std::ostream& operator<<(std::ostream& ostr, IntArrayList& rhs)
{
  ostr << "[";
  if(rhs.size_ > 0) {
    for (size_t i = 0; i < (rhs.size_ - 1); i++) {
      ostr << rhs.arr_[i] << ", ";
    }
    ostr << rhs.arr_[rhs.size_ - 1];
  }
  ostr << "]";
  return ostr;
}