#include "error.h"
#include <string.h>
#include <gc/gc.h>

void error_exit(error_t e, const char *msg, ...) {
	va_list ap;

	va_start(ap, msg);
	vfprintf(stderr, msg, ap);
	va_end(ap);

	exit(e);
}

void perror_exit(error_t e, const char *msg) {
	perror(msg);
	exit(e);
}

void *xmalloc(size_t l) {
	void *r = GC_malloc(l);
	if(!r)
		perror_exit(ERROR_SYSTEM, "GC_alloc");
	return r;
}

char *xstrdup(const char *s) {
	char * p = GC_strdup(s);
	if (!p)
		perror_exit(ERROR_SYSTEM, "GC_strdup");
	return p;
}

char *xstrndup(const char *s, int n) {
	char *p = GC_malloc_atomic(n + 1);
	if (!p)
		perror_exit(ERROR_SYSTEM, "gc_malloc_atomic");
	memcpy(p, s, n);
	p[n] = 0;
	return p;
}

char *xstrcat(const char *s1, const char *s2) {
	size_t s1len = strlen(s1);
	size_t s2len = strlen(s2);
	char *s = GC_malloc_atomic(s1len + s2len + 1);
	memcpy(s, s1, s1len);
	memcpy(s + s1len, s2, s2len);
	s[s1len + s2len] = 0;
	return s;
}
