/*
 *  hap -- a mail notification program
 * 
 *  copyright 1995 by Eric Fischer, etaoin@uchicago.edu
 * 
 *  copies of hap may be redistributed under the terms of the
 *  GNU public license, copies of which are available from
 *  the Free Software Foundation, 59 Temple Place, Boston, MA
 *  02111 USA.
 *
 */

#include "hap.h"

/*************************************************************************

   MEMORY ALLOCATION STUFF

**************************************************************************/

/* return a pointer to malloc()ed data of size 'big'; die if it fails */

voidptr
xmalloc (big)
	size_t big;
{
	voidptr foo = malloc (big);

	if (foo == 0) {
		fprintf (stderr, "%s: memory failure, %d bytes\n", program,
		    (int) big);
		perror ("malloc");

		sleep (5);
		exit (1);
	}

	return foo;
}

/* like realloc, but die if it fails */

voidptr
xrealloc (old, big)
	voidptr old;
	size_t big;
{
	voidptr foo;

	if (old) foo = realloc (old, big);
	else foo = xmalloc (big);

	if (foo == 0) {
		fprintf (stderr, "%s: memory failure, %d bytes\n", program,
		    (int) big);
		perror ("realloc");

		sleep (5);
		exit (1);
	}

	return foo;
}

/* reallocate string 'old' to large enough to hold its current contents 
   plus whatever's in 'new', and concatenate 'new' onto the end of it.
   then return the new address of 'old'.  This gets used a lot.

   if 'old' is null, build a new string from scratch.
*/

char *
addtostr (old, new)
	char *old;
	char *new;
{
	if (new == 0) return old;

	if (old == 0) {
		char *foo = xmalloc ((strlen (new) + 1) * sizeof (char));

		strcpy (foo, new);
		return foo;
	} else {
		old = xrealloc (old, (strlen (old) + strlen (new) + 1) *
		    sizeof (char));

		strcat (old, new);
		return old;
	}
}

/* like addtostr, but use a variable parameter instead of returning it
   so I don't have to type the variable name so often...
*/

void
addstr(old, new)
	char **old;
	char *new;
{
	*old = addtostr(*old, new);
}

/* like addstr, but add just a single character. */

void
addchar (str, c)
	char **str;
	int c;
{
	if (str == 0) return;

	if (*str == 0) {
		*str = xmalloc (2 * sizeof (char));
		(*str)[0] = c;
		(*str)[1] = 0;
		return;
	} else {
		int len = strlen (*str);

		*str = xrealloc (*str, (strlen (*str) + 2) * sizeof (char));
		(*str)[len] = c;
		(*str)[len + 1] = 0;
	}
}

