#pragma implementation
#include <std.h>
#include "tempbuf.h"

void TempBuf::set_size(int new_size, int fill /* = -1 */)
{
    if (new_size > size()) { 
	extend(new_size - (_lim - _base));
	if (fill >= 0) {
	    register char *ptr = _ptr;
	    for (int i = new_size - size(); --i >= 0; ) *ptr++ = fill;
	}
    }
    _ptr = _base + new_size;
}

char * TTempBuf::copy(int add_nul /* = 1*/) const
{
    int len = size();
    char *str = (char*)malloc(len + add_nul);
    memcpy(str, _base, len);
    if (add_nul) str[len] = '\0';
    return str;    
}

void TTempBuf::extend(int needed)
{
    if (needed <= 0)
	return;
    int old_len = size();
    int new_len = 2*old_len;
    if (old_len + needed < new_len)new_len = old_len + needed;
    if (_base == _short_buf) {
	_base = (char*)malloc(new_len);
	memcpy(_base, _short_buf, old_len);
	_ptr = _base + TEMP_SHORT_BUF;
	_lim = _base + 2*TEMP_SHORT_BUF;
    } else {
	_base = (char*)realloc(_base, new_len);
    }
    _ptr = _base + old_len;
    _lim = _base + new_len;
}
