#include "netbuffer"

void Netbuffer::check_space(unsigned extra) {
    PROFILE("Netbuffer::check_space");

    if (!buf_alloced) {
	buf_alloced = extra;
	// When the first network buffer is allocated in HTTP mode, get
	// twice as much. Most often that will be enough to fetch the whole
	// client request, so that one realloc() will be spared.
	if (extra == config.buffersize() &&
	    config.stype() == Servertype::t_http)
	    buf_alloced <<= 1;
	debugmsg("Netbuffer: reserving " << buf_alloced <<
		  " bytes for network buffer\n");
	LOCK_MALLOC;
	buf_data = (char*)malloc(buf_alloced);
	UNLOCK_MALLOC;
	if (! buf_data)
	    throw Error("Memory fault in Netbuffer::check_space");
    } else if (buf_sz + extra > buf_alloced) {
	debugmsg("Netbuffer: reallocating net buffer from " <<
		 buf_alloced << " to " <<
		 (buf_alloced + extra) << " bytes\n");
	buf_alloced += extra;
	LOCK_MALLOC;
	buf_data = (char*)realloc(buf_data, buf_alloced);
	UNLOCK_MALLOC;
	if (! buf_data)
	    throw Error("Memory fault in Netbuffer::check_space");
    }
}
