// file      : xsde/cxx/string-sequence.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2005-2007 Code Synthesis Tools CC
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#include <string.h> // memcpy, strlen, strcmp

#include <xsde/cxx/string-sequence.hxx>

namespace xsde
{
  namespace cxx
  {
    string_sequence::
    ~string_sequence ()
    {
      for (char** p = data_; p < data_ + size_; ++p)
        delete[] *p;

      delete[] data_;
    }

#ifdef XSDE_EXCEPTIONS
    void string_sequence::
    push_back (const char* cs)
    {
      size_t n = strlen (cs) + 1;
      char* s = new char[n];
      memcpy (s, cs, n);

      if (capacity_ < size_ + 1)
        grow ();

      data_[size_++] = s;
    }
#else
    string_sequence::error string_sequence::
    push_back (const char* cs)
    {
      size_t n = strlen (cs) + 1;
      char* s = new char[n];

      if (s == 0)
        return error_no_memory;

      memcpy (s, cs, n);

      error r = error_none;

      if (capacity_ < size_ + 1)
        r = grow ();

      if (r == error_none)
        data_[size_++] = s;
      else
        delete[] s;

      return r;
    }
#endif

#ifdef XSDE_EXCEPTIONS
    void string_sequence::
    grow ()
    {
      size_t c = capacity_ != 0 ? capacity_ * 2 : 16;
      char** d = new char*[c];

      if (size_)
        memcpy (d, data_, size_ * sizeof (char*));

      delete[] data_;

      data_ = d;
      capacity_ = c;
    }
#else
    string_sequence::error string_sequence::
    grow ()
    {
      size_t c = capacity_ != 0 ? capacity_ * 2 : 16;
      char** d = new char*[c];

      if (d == 0)
        return error_no_memory;

      if (size_)
        memcpy (d, data_, size_ * sizeof (char*));

      delete[] data_;

      data_ = d;
      capacity_ = c;

      return error_none;
    }
#endif

    bool
    operator== (const string_sequence& x, const string_sequence& y)
    {
      if (x.size () != y.size ())
        return false;

      for (size_t i = 0; i < x.size (); ++i)
        if (strcmp (x[i], y[i]) != 0)
          return false;

      return true;
    }
  }
}
