54 return result; |
54 return result; |
55 } |
55 } |
56 |
56 |
57 void *flib_malloc(size_t size) { |
57 void *flib_malloc(size_t size) { |
58 void *result = malloc(size); |
58 void *result = malloc(size); |
59 if(!result) { |
59 if(!result && size>0) { |
60 flib_log_e("Out of memory trying to malloc %zu bytes.", size); |
60 flib_log_e("Out of memory trying to malloc %zu bytes.", size); |
61 } |
61 } |
62 return result; |
62 return result; |
63 } |
63 } |
64 |
64 |
65 void *flib_calloc(size_t count, size_t elementsize) { |
65 void *flib_calloc(size_t count, size_t elementsize) { |
66 void *result = calloc(count, elementsize); |
66 void *result = calloc(count, elementsize); |
67 if(!result) { |
67 if(!result && count>0 && elementsize>0) { |
68 flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize); |
68 flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize); |
|
69 } |
|
70 return result; |
|
71 } |
|
72 |
|
73 void *flib_realloc(void *ptr, size_t size) { |
|
74 void *result = realloc(ptr, size); |
|
75 if(!result && size>0) { |
|
76 flib_log_e("Out of memory trying to realloc %zu bytes.", size); |
69 } |
77 } |
70 return result; |
78 return result; |
71 } |
79 } |
72 |
80 |
73 static bool isAsciiAlnum(char c) { |
81 static bool isAsciiAlnum(char c) { |
74 return (c>='0' && c<='9') || (c>='a' && c <='z') || (c>='A' && c <='Z'); |
82 return (c>='0' && c<='9') || (c>='a' && c <='z') || (c>='A' && c <='Z'); |
75 } |
83 } |
76 |
84 |
77 char *flib_urlencode(const char *inbuf) { |
85 char *flib_urlencode(const char *inbuf) { |
|
86 return flib_urlencode_pred(inbuf, isAsciiAlnum); |
|
87 } |
|
88 |
|
89 char *flib_urlencode_pred(const char *inbuf, bool (*needsEscaping)(char c)) { |
78 if(!inbuf) { |
90 if(!inbuf) { |
79 return NULL; |
91 return NULL; |
80 } |
92 } |
81 size_t insize = strlen(inbuf); |
93 size_t insize = strlen(inbuf); |
82 if(insize > SIZE_MAX/4) { |
94 if(insize > SIZE_MAX/4) { |
89 return NULL; |
101 return NULL; |
90 } |
102 } |
91 |
103 |
92 size_t inpos = 0, outpos = 0; |
104 size_t inpos = 0, outpos = 0; |
93 while(inbuf[inpos]) { |
105 while(inbuf[inpos]) { |
94 if(isAsciiAlnum(inbuf[inpos])) { |
106 if(!needsEscaping(inbuf[inpos])) { |
95 outbuf[outpos++] = inbuf[inpos++]; |
107 outbuf[outpos++] = inbuf[inpos++]; |
96 } else { |
108 } else { |
97 if(snprintf(outbuf+outpos, 4, "%%%02X", (unsigned)((uint8_t*)inbuf)[inpos])<0) { |
109 if(snprintf(outbuf+outpos, 4, "%%%02X", (unsigned)((uint8_t*)inbuf)[inpos])<0) { |
98 flib_log_e("printf error in flib_urlencode"); |
110 flib_log_e("printf error in flib_urlencode"); |
99 free(outbuf); |
111 free(outbuf); |