tisp

tiny lisp
git clone git://edryd.org/tisp
Log | Files | Refs | LICENSE

util.c (910B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <assert.h>
      3 #include <stdarg.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <string.h>
      7 
      8 #include "util.h"
      9 
     10 void *
     11 ecalloc(size_t nmemb, size_t size)
     12 {
     13 	void *p;
     14 
     15 	if (!(p = calloc(nmemb, size)))
     16 		die(1, "calloc:");
     17 
     18 	return p;
     19 }
     20 
     21 void *
     22 emalloc(size_t size)
     23 {
     24 	void *p;
     25 
     26 	if (!(p = malloc(size)))
     27 		die(1, "malloc:");
     28 
     29 	return p;
     30 }
     31 
     32 void *
     33 erealloc(void *p, size_t size)
     34 {
     35 	if (!(p = realloc(p, size)))
     36 		die(1, "realloc:");
     37 
     38 	return p;
     39 }
     40 
     41 char *
     42 estrdup(char *s)
     43 {
     44 	if (!(s = strdup(s)))
     45 		die(1, "strdup:");
     46 
     47 	return s;
     48 }
     49 
     50 void
     51 efree(void *p)
     52 {
     53 	if (p)
     54 		free(p);
     55 }
     56 
     57 void
     58 die(int eval, const char *fmt, ...)
     59 {
     60 	va_list ap;
     61 
     62 	va_start(ap, fmt);
     63 	vfprintf(stderr, fmt, ap);
     64 	va_end(ap);
     65 
     66 	if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
     67 		fputc(' ', stderr);
     68 		perror(NULL);
     69 	} else {
     70 		fputc('\n', stderr);
     71 	}
     72 
     73 	if (eval > -1)
     74 		exit(eval);
     75 }