/*
 * $Id$
 *
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *
 *     Main file of mr_mem : a very small and simple
 *     library for memory management
 *
 * Provided under the GPLv2
 */

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

#include "mr_err.h"
#include "mr_msg.h"

/*
 * Function that frees memory if necessary
 */
void mr_free(void *allocated) {

	/* free man pages says that if allocated is NULL 
	 * nothing happens 
	 */
	free(allocated);
	allocated = NULL;
}

/* encapsulation function for malloc */
void *mr_malloc(size_t size) {
	
	void *ret;

	ret = malloc(size);
	if (ret == NULL) {
		mr_log_exit(-1,"Unable to alloc memory in mr_malloc\nExiting...");
	}
}

/* encapsulation function for getline */
void mr_getline(char **lineptr, size_t *n, FILE *stream) {
	
	ssize_t ret;

	ret = getline(lineptr,n,stream);
	if (ret == -1) {
		mr_log_exit(-1,"Unable to alloc memory in mr_getline\nExiting...");
	}
}


/* encapsulation function for vasprintf */
void mr_vasprintf(char **strp, const char *fmt, va_list ap) {

	int res = 0;
	va_list args;

	res = vasprintf(strp, fmt, ap);
	if (res == -1) {
		mr_log_exit(-1,"Unable to alloc memory in mr_vasprintf\nExiting...");
	}
}

/* encapsulation function for asprintf */
void mr_asprintf(char **strp, const char *fmt, ...) {

	int res = 0;
	va_list args;

	va_start(args, fmt);
	res = asprintf(strp, fmt, args);
	if (res == -1) {
		mr_log_exit(-1,"Unable to alloc memory in mr_asprintf\nExiting...");
	}
	va_end(args);
}

/*
 * Function that properly allocates a string from another one
 * freeing it before in any case
 */
void mr_allocstr(char *alloc, const char *orig) {

	mr_free((void *)alloc); 
	mr_asprintf(&alloc, orig);
}
