1 #ifndef __REDISEARCH_ALLOC__
2 #define __REDISEARCH_ALLOC__
3
4 #include <stdlib.h>
5 #include <string.h>
6 #include <stdarg.h>
7 #include "redismodule.h"
8
9 #ifdef REDIS_MODULE_TARGET /* Set this when compiling your code as a module */
10
rm_malloc(size_t n)11 static inline void *rm_malloc(size_t n) {
12 return RedisModule_Alloc(n);
13 }
rm_calloc(size_t nelem,size_t elemsz)14 static inline void *rm_calloc(size_t nelem, size_t elemsz) {
15 return RedisModule_Calloc(nelem, elemsz);
16 }
rm_realloc(void * p,size_t n)17 static inline void *rm_realloc(void *p, size_t n) {
18 if (n == 0) {
19 RedisModule_Free(p);
20 return NULL;
21 }
22 return RedisModule_Realloc(p, n);
23 }
rm_free(void * p)24 static inline void rm_free(void *p) {
25 RedisModule_Free(p);
26 }
rm_strdup(const char * s)27 static inline char *rm_strdup(const char *s) {
28 return RedisModule_Strdup(s);
29 }
30
rm_strndup(const char * s,size_t n)31 static char *rm_strndup(const char *s, size_t n) {
32 char *ret = (char *)rm_malloc(n + 1);
33
34 if (ret) {
35 ret[n] = '\0';
36 memcpy(ret, s, n);
37 }
38 return ret;
39 }
40
rm_vasprintf(char ** __restrict __ptr,const char * __restrict __fmt,va_list __arg)41 static int rm_vasprintf(char **__restrict __ptr, const char *__restrict __fmt, va_list __arg) {
42 va_list args_copy;
43 va_copy(args_copy, __arg);
44
45 size_t needed = vsnprintf(NULL, 0, __fmt, __arg) + 1;
46 *__ptr = (char *)rm_malloc(needed);
47
48 int res = vsprintf(*__ptr, __fmt, args_copy);
49
50 va_end(args_copy);
51
52 return res;
53 }
54
rm_asprintf(char ** __ptr,const char * __restrict __fmt,...)55 static int rm_asprintf(char **__ptr, const char *__restrict __fmt, ...) {
56 va_list ap;
57 va_start(ap, __fmt);
58
59 int res = rm_vasprintf(__ptr, __fmt, ap);
60
61 va_end(ap);
62
63 return res;
64 }
65 #endif
66 #ifndef REDIS_MODULE_TARGET
67 /* for non redis module targets */
68 #define rm_malloc malloc
69 #define rm_free free
70 #define rm_calloc calloc
71 #define rm_realloc realloc
72 #define rm_strdup strdup
73 #define rm_strndup strndup
74 #define rm_asprintf asprintf
75 #define rm_vasprintf vasprintf
76 #endif
77
78 #define rm_new(x) rm_malloc(sizeof(x))
79
80 #endif /* __RMUTIL_ALLOC__ */
81