equal
deleted
inserted
replaced
1 #include "util.h" |
1 #include "util.h" |
|
2 #include "logging.h" |
2 |
3 |
3 #include <stddef.h> |
4 #include <stddef.h> |
4 #include <stdarg.h> |
5 #include <stdarg.h> |
5 #include <stdlib.h> |
6 #include <stdlib.h> |
6 #include <string.h> |
7 #include <string.h> |
14 return result; |
15 return result; |
15 } |
16 } |
16 |
17 |
17 char *flib_vasprintf(const char *fmt, va_list args) { |
18 char *flib_vasprintf(const char *fmt, va_list args) { |
18 char *result = NULL; |
19 char *result = NULL; |
19 int requiredSize = vsnprintf(NULL, 0, fmt, args)+1; // Figure out how much memory we need, |
20 if(!fmt) { |
20 if(requiredSize>=0) { |
21 flib_log_e("null parameter in flib_vasprintf"); |
21 char *tmpbuf = malloc(requiredSize); // allocate it |
22 } else { |
22 if(tmpbuf) { |
23 int requiredSize = vsnprintf(NULL, 0, fmt, args)+1; // Figure out how much memory we need, |
23 if(vsnprintf(tmpbuf, requiredSize, fmt, args)>=0) { // and then do the actual formatting. |
24 if(requiredSize<0) { |
|
25 flib_log_e("Error formatting string with template \"%s\" in flib_vasprintf", fmt); |
|
26 } else { |
|
27 char *tmpbuf = flib_malloc(requiredSize); // allocate it |
|
28 if(tmpbuf && vsnprintf(tmpbuf, requiredSize, fmt, args)>=0) { // and then do the actual formatting. |
24 result = tmpbuf; |
29 result = tmpbuf; |
25 tmpbuf = NULL; |
30 tmpbuf = NULL; |
26 } |
31 } |
|
32 free(tmpbuf); |
27 } |
33 } |
28 free(tmpbuf); |
|
29 } |
34 } |
30 return result; |
35 return result; |
31 } |
36 } |
32 |
37 |
33 char *flib_strdupnull(const char *str) { |
38 char *flib_strdupnull(const char *str) { |
39 |
44 |
40 void *flib_bufdupnull(const void *buf, size_t size) { |
45 void *flib_bufdupnull(const void *buf, size_t size) { |
41 if(!buf || size==0) { |
46 if(!buf || size==0) { |
42 return NULL; |
47 return NULL; |
43 } |
48 } |
44 void *result = malloc(size); |
49 void *result = flib_malloc(size); |
45 if(result) { |
50 if(result) { |
46 memcpy(result, buf, size); |
51 memcpy(result, buf, size); |
47 } |
52 } |
48 return result; |
53 return result; |
49 } |
54 } |
|
55 |
|
56 void *flib_malloc(size_t size) { |
|
57 void *result = malloc(size); |
|
58 if(!result) { |
|
59 flib_log_e("Out of memory trying to malloc %zu bytes.", size); |
|
60 } |
|
61 return result; |
|
62 } |
|
63 |
|
64 void *flib_calloc(size_t count, size_t elementsize) { |
|
65 void *result = calloc(count, elementsize); |
|
66 if(!result) { |
|
67 flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize); |
|
68 } |
|
69 return result; |
|
70 } |