From 9cf4667331b97f1123f4156273a46558e27c2d2d Mon Sep 17 00:00:00 2001 From: "@syxhe" Date: Mon, 21 Apr 2025 17:31:37 -0500 Subject: Start work on cqueue implementation, create cleanup set of functions --- src/shared.c | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) (limited to 'src/shared.c') 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) { free(tmp); return actual; +} + + +int cleanup_init(cleanup * const loc, int size, cleanup_callback funcs[], void *args[]) { + if(!loc) + RETURNWERR(EINVAL, -1); + if(size < 1) + RETURNWERR(EINVAL, -1); + if(!funcs) + RETURNWERR(EINVAL, -1); + if(!args) + RETURNWERR(EINVAL, -1); + + loc->funcs = funcs; + loc->args = args; + loc->size = size; + loc->used = 0; + + return 0; +} + +int cleanup_register(cleanup * const loc, cleanup_callback cb, void *arg) { + if(!loc) + RETURNWERR(EINVAL, -1); + if(loc->used >= loc->size) + RETURNWERR(ENOMEM, -1); + if(!cb) + RETURNWERR(EINVAL, -1); + + loc->funcs[loc->used] = cb; + loc->args[loc->used] = arg; + loc->used++; + + return 0; +} + +int cleanup_cndregister(cleanup * const loc, unsigned char flag, cleanup_callback cb, void *arg) { + if(flag) + return 0; + + if(!loc) + RETURNWERR(EINVAL, -1); + if(loc->used >= loc->size) + RETURNWERR(ENOMEM, -1); + if(!cb) + RETURNWERR(EINVAL, -1); + + loc->funcs[loc->used] = cb; + loc->args[loc->used] = arg; + loc->used++; + + return 0; +} + +int cleanup_clear(cleanup * const loc) { + if(!loc) + RETURNWERR(EINVAL, -1); + + loc->used = 0; + return 0; +} + +cleanup_callback cleanup_peekf(cleanup * const loc) { + if(!loc) + RETURNWERR(EINVAL, NULL); + if(loc->used == 0) + RETURNWERR(ENODATA, NULL); + + return loc->funcs[loc->used - 1]; +} +cleanup_callback cleanup_popf(cleanup * const loc) { + cleanup_callback cb = cleanup_peekf(loc); + if(cb == NULL) + RETURNWERR(EINVAL, NULL); + + loc->used--; + + return cb; +} + +void * cleanup_peeka(cleanup * const loc) { + if(!loc) + RETURNWERR(EINVAL, NULL); + if(loc->used == 0) + RETURNWERR(ENODATA, NULL); + + return loc->args[loc->used - 1]; +} +void * cleanup_popa(cleanup * const loc) { + void *mem = cleanup_peeka(loc); + if(!mem) + RETURNWERR(EINVAL, NULL); + + loc->used--; + + return mem; +} + +int cleanup_fire(cleanup * const loc) { + if(!loc) + RETURNWERR(EINVAL, -1); + + for(int i = (loc->used - 1); i >= 0; i--) + loc->funcs[i](loc->args[i]); + loc->used = 0; + + return 0; } \ No newline at end of file -- cgit v1.2.3