/* 
 * Copyright (C) 2000-2001 Computer & Communications Research Laboratories,
 *			   Industrial Technology Research Institute
 */
/* Copyright Telcordia Technologies 1999 */
/* 
 * adtStr.c
 *
 * $Id: adtStr.c,v 1.2 2001/06/12 00:36:54 hcc Exp $
 *
 * Handles allocation, freeing, and quick append from char*
 */

#include "adtStr.h"
#include <stdlib.h>
#include <string.h>

struct adtStrObj
{
    char* text;
    long  len, alloced;
};

adtStr adtStrNew() 
{
    adtStr _this;
    _this = malloc(sizeof *_this);
    /* ErrorCheck */

    _this->len = 0;
    _this->alloced = MINALLOC;
    _this->text = malloc(MINALLOC);
    adtStrClr(_this);

    return _this;
}

int  adtStrLen(adtStr _this)
{
    return _this->len;
}

void adtStrClr(adtStr _this)
{
    _this->len = 0;
    _this->text[0] = '\0';
}

void adtStrFree(adtStr _this)
{
    if( _this==NULL ) return;

    free(_this->text);
    free(_this);
}

void adtStrCatN(adtStr _this, char* s, int n)
{
    long newLen;
    char *from, *to;
    if( s==NULL ) return;

    newLen = _this->len+n;
    if( newLen >= _this->alloced ) {
		while( newLen >= _this->alloced ) {
			_this->alloced = (long)(_this->alloced * 1.5);
		}
		_this->text = realloc(_this->text, _this->alloced);
		/* ErrorCheck */
    }

    /* strncpy((_this->text) + (_this->len), s, n); */
    /* need to determine real length copied and append '\0' 
     * n is number of characters left to copy.  if non-zero at end,
     * length was less than expected.
     */
    from = s;
    to = (_this->text) + (_this->len);
    while( *from!='\0'  && n>0 ) {
		*to = *from; to++; from++;
		n--;
    }
    *to = '\0';
    _this->len = newLen-n; 
}

void adtStrCat(adtStr _this, char* msg)
{
    long newLen;
    if( msg==NULL ) return;

    newLen = _this->len+strlen(msg);
    if( newLen >= _this->alloced ) {
		while( newLen >= _this->alloced ) {
			_this->alloced = (long)(_this->alloced * 1.5);
		}
		_this->text = realloc(_this->text, _this->alloced);
		/* ErrorCheck */
    }

    strcpy((_this->text) + (_this->len), msg);
    _this->len = newLen; 
}

char*adtStrAsCStr(adtStr _this)
{
    return _this->text;
}
