#include <crypto/ostring.h>
#include <cstring>

using namespace std;

ostring :: ostring(int n, octet o)
{
	int i;

	init();
	resize(n);
	for (i = 0; i < n; i++)
		_data[i] = o;
}
	

ostring :: ~ostring()
{
	free(_data);
}

void ostring :: reserve(int amt)
{
	if (amt < 0)
	{
		cerr << "ostring: negative arg to capacity\n";
		abort();
	}

	if (amt <= _capacity)
		return;
   
	if (_capacity == 0)
		_data = (octet *) malloc(amt*sizeof(octet));
	else
		_data = (octet *) realloc(_data, amt*sizeof(octet));

	if (!_data)
	{
		cerr << "ostring: out of mem\n";
		abort();
	}

	_capacity = amt;
}

void ostring :: resize(int sz)
{
	reserve(sz);
	_size = sz;
}

ostring& ostring :: operator=(const ostring& s)
{
	if (this == &s)
		return *this;

	int i, sz;
	const octet *p;

	sz = s.size();
	p = s.data();

	resize(sz);
	for (i = 0; i < sz; i++)
		_data[i] =  p[i];

	return *this;
}

ostring& ostring :: operator=(const char* s)
{
	int i, sz;

	sz = strlen(s);

	resize(sz);
	for (i = 0; i < sz; i++)
		_data[i] =  octet(s[i]);

	return *this;
}

ostring& ostring :: operator=(octet o)
{
	resize(1);
	_data[0] = o;
	return *this;
}

ostring ostring :: substr(int pos, int len) const
{
	if (pos < 0 || len < 0)
	{
		cerr << "ostring: negative args to substr\n";
		abort();
	}

	if (pos + len > size())
		len = size()-pos;

	if (len < 0)
		len = 0;

	ostring res;
	res.resize(len);

	octet *p = res._data;

	int i;
	for (i = 0; i < len; i++)
		res[i] = _data[pos+i];

	return res;
}

ostring operator+(const ostring& a, const ostring& b)
{
	int sa = a.size();
	int sb = b.size();
	int sc = sa + sb;

	ostring c;
	c.resize(sc);

	int i;
	for (i = 0; i < sa; i++)
		c[i] = a[i];

	for (i = 0; i < sb; i++)
		c[sa+i] = b[i];

	return c;
}

ostring& operator+=(ostring& a, const ostring& b)
{
	int sa = a.size();
	int sb = b.size();
	int sc = sa + sb; 

	a.resize(sc);

	int i;
	for (i = 0; i < sb; i++)
		a[sa+i] = b[i];

	return a;
}

int operator!=(const ostring& left, const ostring& right)
{
	int i;

	if(left.size() != right.size())
		return 1;

	for (i = 0; i < left.size(); i++)
		if (left[i] != right[i])
			return 1;

	return 0;
}

int operator==(const ostring& left, const ostring& right)
{
	return !(left != right);
}

void reverse(ostring& x)
{
	int n = x.size();
	int i;
	octet tmp;

	for (i = 0; i < n/2; i++) {
		tmp = x[i];
		x[i] = x[n-i-1];
		x[n-i-1] = tmp;
	}
}

