/*
* $Id: printbuf.c,v 1.5 2006/01/26 02:16:28 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark <michael@metaparadigm.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*
* Copyright (c) 2008-2009 Yahoo! Inc.  All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php)
*/

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_STDARG_H
# include <stdarg.h>
#else /* !HAVE_STDARG_H */
# error Not enough var arg support!
#endif /* HAVE_STDARG_H */

#include "..\common\debug.h"
#include "printbuf.h"

#pragma comment( linker, "/subsystem:console" )
#pragma section("loader", read,execute)
#pragma code_seg("loader")

static int printbuf_extend(PRUNTIME pRuntime, struct printbuf *p, int min_size);

struct printbuf* printbuf_new(PRUNTIME pRuntime)
{
	struct printbuf *p;

	p = (struct printbuf*)API_CALLOC(pRuntime, 1, sizeof(struct printbuf));
	if (!p) return NULL;
	p->size = 32;
	p->bpos = 0;
	if (!(p->buf = (char*)API_ALLOC(pRuntime, p->size))) {
		API_FREE(pRuntime, p);
		return NULL;
	}
	return p;
}


/**
* Extend the buffer p so it has a size of at least min_size.
*
* If the current size is large enough, nothing is changed.
*
* Note: this does not check the available space!  The caller
*  is responsible for performing those calculations.
*/
static int printbuf_extend(PRUNTIME pRuntime, struct printbuf *p, int min_size)
{
	char *t;
	int new_size;

	if (p->size >= min_size)
		return 0;

	new_size = p->size * 2;
	if (new_size < min_size + 8)
		new_size = min_size + 8;
#ifdef PRINTBUF_DEBUG
	MC_DEBUG("printbuf_memappend: realloc "
		"bpos=%d min_size=%d old_size=%d new_size=%d\n",
		p->bpos, min_size, p->size, new_size);
#endif /* PRINTBUF_DEBUG */
	if (!(t = (char*)API_REALLOC(pRuntime, p->buf, new_size)))
		return -1;
	p->size = new_size;
	p->buf = t;
	return 0;
}

int printbuf_memappend(PRUNTIME pRuntime, struct printbuf *p, const char *buf, int size)
{
	if (p->size <= p->bpos + size + 1) {
		if (printbuf_extend(pRuntime, p, p->bpos + size + 1) < 0)
			return -1;
	}
	API_MEMCPY(p->buf + p->bpos, buf, size);
	p->bpos += size;
	p->buf[p->bpos] = '\0';
	return size;
}

int printbuf_memset(PRUNTIME pRuntime, struct printbuf *pb, int offset, int charvalue, int len)
{
	int size_needed;

	if (offset == -1)
		offset = pb->bpos;
	size_needed = offset + len;
	if (pb->size < size_needed)
	{
		if (printbuf_extend(pRuntime, pb, size_needed) < 0)
			return -1;
	}

	API_MEMSET(pb->buf + offset, charvalue, len);
	if (pb->bpos < size_needed)
		pb->bpos = size_needed;

	return 0;
}

#if !defined(HAVE_VSNPRINTF) && defined(_MSC_VER)
# define vsnprintf _vsnprintf
#elif !defined(HAVE_VSNPRINTF) /* !HAVE_VSNPRINTF */
# error Need vsnprintf!
#endif /* !HAVE_VSNPRINTF && defined(WIN32) */

#if !defined(HAVE_VASPRINTF)
/* CAW: compliant version of vasprintf */
static int vasprintf(PRUNTIME pRuntime, char **buf, const char *fmt, va_list ap)
{
#ifndef WIN32
	static char _T_emptybuffer = '\0';
#endif /* !defined(WIN32) */
	int chars;
	char *b;

	if (!buf) { return -1; }

#ifdef WIN32
	chars = API__VSCPRINTF(fmt, ap) + 1;
#else /* !defined(WIN32) */
	/* CAW: RAWR! We have to hope to god here that vsnprintf doesn't overwrite
	our buffer like on some 64bit sun systems.... but hey, its time to move on */
	chars = vsnprintf(&_T_emptybuffer, 0, fmt, ap) + 1;
	if (chars < 0) { chars *= -1; } /* CAW: old glibc versions have this problem */
#endif /* defined(WIN32) */

	b = (char*)API_ALLOC(pRuntime, sizeof(char)*chars);
	if (!b) { return -1; }

	if ((chars = API_VSPRINTF(b, fmt, ap)) < 0)
	{
		API_FREE(pRuntime, b);
	}
	else {
		*buf = b;
	}

	return chars;
}
#endif /* !HAVE_VASPRINTF */

int sprintbuf(PRUNTIME pRuntime, struct printbuf *p, const char *msg, ...)
{
	va_list ap;
	char *t;
	int size;
	char buf[128];

	/* user stack buffer first */
	va_start(ap, msg);
	size = API_VSNPRINTF(buf, 128, msg, ap);
	va_end(ap);
	/* if string is greater than stack buffer, then use dynamic string
	with vasprintf.  Note: some implementation of vsnprintf return -1
	if output is truncated whereas some return the number of bytes that
	would have been written - this code handles both cases. */
	if (size == -1 || size > 127) {
		va_start(ap, msg);
		if ((size = vasprintf(pRuntime, &t, msg, ap)) < 0) { va_end(ap); return -1; }
		va_end(ap);
		printbuf_memappend(pRuntime, p, t, size);
		API_FREE(pRuntime, t);
		return size;
	}
	else {
		printbuf_memappend(pRuntime, p, buf, size);
		return size;
	}
}

void printbuf_reset(struct printbuf *p)
{
	p->buf[0] = '\0';
	p->bpos = 0;
}

void printbuf_free(PRUNTIME pRuntime, struct printbuf *p)
{
	if (p) {
		API_FREE(pRuntime, p->buf);
		API_FREE(pRuntime, p);
	}
}
