rcx

miscellaneous C library
git clone git://git.rr3.xyz/rcx
Log | Files | Refs | README | LICENSE

alloc.c (2047B)


      1 #include <errno.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #include "alloc.h"
      6 #include "log.h"
      7 #include "rcx.h"
      8 
      9 #include "internal/util.h"
     10 
     11 void *
     12 r_alloc(usize size) {
     13 	void *p = malloc(size);
     14 	if (!p) errno = ENOMEM;
     15 	return p;
     16 }
     17 
     18 void *
     19 r_allocz(usize size) {
     20 	void *p = calloc(1, size);
     21 	if (!p) errno = ENOMEM;
     22 	return p;
     23 }
     24 
     25 void *
     26 r_allocn(usize len, usize size) {
     27 	if (r_mul_will_overflow_(len, size)) {
     28 		errno = ENOMEM;
     29 		return 0;
     30 	}
     31 	return r_alloc(len * size);
     32 }
     33 
     34 void *
     35 r_allocnz(usize len, usize size) {
     36 	void *p = calloc(len, size);
     37 	if (!p) errno = ENOMEM;
     38 	return p;
     39 }
     40 
     41 int
     42 r_realloc(void *p, usize size) {
     43 	void *q = realloc(*(void **)p, size);
     44 	if (!q) {
     45 		errno = ENOMEM;
     46 		return -1;
     47 	}
     48 	*(void **)p = q;
     49 	return 0;
     50 }
     51 
     52 int
     53 r_reallocz(void *p, usize osize, usize nsize) {
     54 	int ret = r_realloc(p, nsize);
     55 	if (ret == 0 && nsize > osize)
     56 		memset(*(char **)p + osize, 0, nsize - osize);
     57 	return ret;
     58 }
     59 
     60 int
     61 r_reallocn(void *p, usize len, usize size) {
     62 	if (r_mul_will_overflow_(len, size)) {
     63 		errno = ENOMEM;
     64 		return -1;
     65 	}
     66 	return r_realloc(p, len * size);
     67 }
     68 
     69 int
     70 r_reallocnz(void *p, usize olen, usize nlen, usize size) {
     71 	if (r_mul_will_overflow_(nlen, size)) {
     72 		errno = ENOMEM;
     73 		return -1;
     74 	}
     75 	return r_reallocz(p, olen * size, nlen * size);
     76 }
     77 
     78 #define EALLOC(mods, ...)\
     79 	void *r_ealloc##mods(__VA_ARGS__) {\
     80 		void *q = r_alloc##mods(EALLOC_AUX
     81 #define EALLOC_AUX(...)\
     82 			__VA_ARGS__);\
     83 		if (!q) r_fatalf("allocation failure");\
     84 		return q;\
     85 	}
     86 
     87 EALLOC(, usize size)(size)
     88 EALLOC(z, usize size)(size)
     89 EALLOC(n, usize len, usize size)(len, size)
     90 EALLOC(nz, usize len, usize size)(len, size)
     91 
     92 #define EREALLOC(mods, ...)\
     93 	int r_erealloc##mods(void *p, __VA_ARGS__) {\
     94 		int ret = r_realloc##mods(p, EREALLOC_AUX
     95 #define EREALLOC_AUX(...)\
     96 			__VA_ARGS__);\
     97 		if (ret < 0) r_fatalf("allocation failure");\
     98 		return 0;\
     99 	}
    100 
    101 EREALLOC(, usize size)(size)
    102 EREALLOC(z, usize osize, usize nsize)(osize, nsize)
    103 EREALLOC(n, usize len, usize size)(len, size)
    104 EREALLOC(nz, usize olen, usize nlen, usize size)(olen, nlen, size)