summaryrefslogtreecommitdiff
path: root/src/shared.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/shared.c')
-rw-r--r--src/shared.c107
1 files changed, 107 insertions, 0 deletions
diff --git a/src/shared.c b/src/shared.c
index bec0354..02fe9a0 100644
--- a/src/shared.c
+++ b/src/shared.c
@@ -221,4 +221,111 @@ char * xdirname(const char * const path) {
221 free(tmp); 221 free(tmp);
222 222
223 return actual; 223 return actual;
224}
225
226
227int cleanup_init(cleanup * const loc, int size, cleanup_callback funcs[], void *args[]) {
228 if(!loc)
229 RETURNWERR(EINVAL, -1);
230 if(size < 1)
231 RETURNWERR(EINVAL, -1);
232 if(!funcs)
233 RETURNWERR(EINVAL, -1);
234 if(!args)
235 RETURNWERR(EINVAL, -1);
236
237 loc->funcs = funcs;
238 loc->args = args;
239 loc->size = size;
240 loc->used = 0;
241
242 return 0;
243}
244
245int cleanup_register(cleanup * const loc, cleanup_callback cb, void *arg) {
246 if(!loc)
247 RETURNWERR(EINVAL, -1);
248 if(loc->used >= loc->size)
249 RETURNWERR(ENOMEM, -1);
250 if(!cb)
251 RETURNWERR(EINVAL, -1);
252
253 loc->funcs[loc->used] = cb;
254 loc->args[loc->used] = arg;
255 loc->used++;
256
257 return 0;
258}
259
260int cleanup_cndregister(cleanup * const loc, unsigned char flag, cleanup_callback cb, void *arg) {
261 if(flag)
262 return 0;
263
264 if(!loc)
265 RETURNWERR(EINVAL, -1);
266 if(loc->used >= loc->size)
267 RETURNWERR(ENOMEM, -1);
268 if(!cb)
269 RETURNWERR(EINVAL, -1);
270
271 loc->funcs[loc->used] = cb;
272 loc->args[loc->used] = arg;
273 loc->used++;
274
275 return 0;
276}
277
278int cleanup_clear(cleanup * const loc) {
279 if(!loc)
280 RETURNWERR(EINVAL, -1);
281
282 loc->used = 0;
283 return 0;
284}
285
286cleanup_callback cleanup_peekf(cleanup * const loc) {
287 if(!loc)
288 RETURNWERR(EINVAL, NULL);
289 if(loc->used == 0)
290 RETURNWERR(ENODATA, NULL);
291
292 return loc->funcs[loc->used - 1];
293}
294cleanup_callback cleanup_popf(cleanup * const loc) {
295 cleanup_callback cb = cleanup_peekf(loc);
296 if(cb == NULL)
297 RETURNWERR(EINVAL, NULL);
298
299 loc->used--;
300
301 return cb;
302}
303
304void * cleanup_peeka(cleanup * const loc) {
305 if(!loc)
306 RETURNWERR(EINVAL, NULL);
307 if(loc->used == 0)
308 RETURNWERR(ENODATA, NULL);
309
310 return loc->args[loc->used - 1];
311}
312void * cleanup_popa(cleanup * const loc) {
313 void *mem = cleanup_peeka(loc);
314 if(!mem)
315 RETURNWERR(EINVAL, NULL);
316
317 loc->used--;
318
319 return mem;
320}
321
322int cleanup_fire(cleanup * const loc) {
323 if(!loc)
324 RETURNWERR(EINVAL, -1);
325
326 for(int i = (loc->used - 1); i >= 0; i--)
327 loc->funcs[i](loc->args[i]);
328 loc->used = 0;
329
330 return 0;
224} \ No newline at end of file 331} \ No newline at end of file