#include "CString.h"

CString::CString (void)
{
  str = NULL;
  len = 0;
  maxlen = (u_short)-1;
}

CString::CString (u_short l)
{
  str = NULL;
  len = 0;
  maxlen = l;
}

CString::CString (c_char s, u_short l)
{
  str = NULL;
  maxlen = l;
  strset (&str, s, maxlen);
  if (str != NULL)
    len = strlen (str);
  else
    len = 0;
}

CString::~CString (void)
{
  my_free (str);
}

void
CString::operator = (c_char s)
{
  strset (&str, s, maxlen);
  if (str != NULL)
    len = strlen (str);
  else
    len = 0;
}

void
CString::operator += (c_char s)
{
  if (s == NULL || s[0] == 0)
    return;
  if (str == NULL)
    {
      *this = s;
      return;
    }
  size_t newlen = strlen (str) + strlen (s);
  if (newlen > maxlen)
    newlen = maxlen;
  char *tmpstr = (char *)my_malloc (newlen+1);
  snprintf (tmpstr, newlen+1, "%s%s", str, s);
  free (str);
  str = tmpstr;
  len = strlen (str);
}

ostream &
operator << (ostream &out, const CString &s)
{
  return out << s.str;
}

bool
CString::operator == (const CString &right) const
{
  if (len != right.len)
    return 0;
  return strcmp (str, right.str) == 0;
}

bool
CString::operator == (c_char right) const
{
  if (right == NULL)
    return str == NULL;
  if (len != strlen (right))
    return 0;
  return strcmp (str, right) == 0;
}

bool
CString::operator |= (const CString &right) const
{
  if (len != right.len)
    return 0;
  return strcasecmp (str, right.str) == 0;
}

bool
CString::operator |= (c_char right) const
{
  if (right == NULL)
    return str == NULL;
  if (len != strlen (right))
    return 0;
  return strcasecmp (str, right) == 0;
}

bool
CString::operator != (c_char right) const
{
  if (right == NULL)
    return str != NULL;
  if (len != strlen (right))
    return 1;
  return strcmp (str, right) != 0;
}

char &
CString::operator [] (u_short pos) const
{
  if (str == NULL || pos > len)
    {
      cerr << "PANIC: out of bounds string access (" << pos << " of " << len << ")\n";
      raise (SIGSEGV);
      exit (1);
    }
  return str[pos];
}

CString::operator bool (void) const
{
  return str != NULL;
}

CString::operator char * (void) const
{
  return str;
}

u_short
CString::getlen (void) const
{
  return len;
}
