/** * @file shared.c * @author syxhe (https://t.me/syxhe) * @brief A collection of functions and macros shared between files, or without a better place * @version 0.1 * @date 2025-06-09 * * @copyright Copyright (c) 2025 * */ #ifndef __VXGG_REWRITE___SHARED_C___3880294315821___ #define __VXGG_REWRITE___SHARED_C___3880294315821___ 1 #define STATIC_ARRAY_LEN(arr) (sizeof((arr))/sizeof((arr)[0])) #define ERRRET(errval, retval) do {\ errno = (errval);\ return (retval);\ } while (0) /// Determines how `vx__alloc()` functions exit. `> 0` calls `error()`, otherwise calls `abort()`. `vx__alloc()` type functions will /// always halt execution #define ___VXGG___VXALLOC_EXIT_ON_ERROR___ 1 /// Determines whether vxgg functions that can error print out a short warning of the error when one is encountered. /// `> 0` will print diagnostic error messages, and will do nothing otherwise #define ___VXGG___VERBOSE_ERRORS___ 1 //! Macro to exit on an alloc error instead of doing the terrible nested if statement that was being used previously #define XALLOC_EXIT(msg, ...) do { \ if(___VXGG___VERBOSE_ERRORS___) error(EXIT_FAILURE, errno, (msg)__VA_ARGS__); \ if(___VXGG___VXALLOC_EXIT_ON_ERROR___) exit(EXIT_FAILURE); \ abort(); \ } while (0) //! Error macro that gcc will not complain about #define ERROR(status, errnum, format, ...) do {error((status), (errnum), (format)__VA_ARGS__); exit((status));} while (0) //! Spit out a warning using `error` #define WARN(errnum, format, ...) do {error(0, (errnum), (format)__VA_ARGS__);} while (0) typedef int (*gcallback)(void*); //!< Generic callback signature typedef void (*fcallback)(void*); //!< free()-like callback signature #include #include #include #include #include /** * @brief Read the entire contents of a file descriptor into a malloc()'ed buffer * * @param str Pointer to a string. Will be replaced with the malloc()'ed string * @param initsize The initial size of the malloc()'ed string * @param fd A file descriptor to read from * @retval (int)[-1, strlen(str)] Returns the size of the array on success, or -1 on error * @note The allocated buffer will expand and contract as necessary, but it's recommended to set `initsize` to some value close to or equal to the size of the file being read to reduce the number of resizes */ int rwbuf(char **str, unsigned long int initsize, int fd) { // Try to read bytes from fd into str // Bytes read == 0, return 0 // Bytes read < 0, free string, return -1; // When string hits capacity, double the capacity, and reallocate the string if(!str || initsize < 1 || fd < 0) ERRRET(EINVAL, -1); char *lstr = NULL, *tmp = NULL; ssize_t bytesread = -1; int csize = initsize, ccap = initsize, eflag = 0; lstr = calloc(initsize, sizeof(char)); if(!lstr) return -1; while((bytesread = read(fd, lstr + (csize - ccap), ccap)) > 0) { ccap -= bytesread; if(ccap <= 0) { csize *= 2; ccap = csize / 2; tmp = realloc(lstr, csize * sizeof(char)); if(!tmp) {eflag = 1; goto ERR_rwbuf;} lstr = tmp; } } if(bytesread < 0) {eflag = 2; goto ERR_rwbuf;} if(lstr) { tmp = realloc(lstr, csize - ccap + 1); if(!tmp) {eflag = 3; goto ERR_rwbuf;} lstr = tmp; } if(lstr && fd == STDIN_FILENO) { lstr[csize - ccap - 1] = '\0'; // Don't include the newline } *str = lstr; return csize - ccap; ERR_rwbuf: if(___VXGG___VERBOSE_ERRORS___) { switch (eflag) { case 1: WARN(errno, "Could not reallocate enough space for lstr",); break; case 2: WARN(errno, "Ran into a read() error",); break; case 3: WARN(errno, "Could not shrink lstr after reading buffer",); break; default: WARN(errno, "Ran into some error",); break; } } free(lstr); return -1; } /** * @brief Write the entire contents of a buffer into a file descriptor * * @param fd The file descriptor to write to * @param buf The buffer to write from * @param len The length of the buffer * @retval (int)[-1, 0] Returns 0 on success, -1 on error */ int wwbuf(int fd, const unsigned char *buf, int len) { if(!buf || len <= 0 || fd < 0) ERRRET(EINVAL, -1); int total = 0; int left = len; int n = -1; while(total < len) { if((n = write(fd, buf + total, left)) < 0) break; total += n; left -= n; } return (n < 0) ? -1 : 0; } // Adapted from Beej's `sendall()` function // https://beej.us/guide/bgnet/html/split/slightly-advanced-techniques.html#sendall // Thanks Beej! /** * @brief `dirname()` reimplementation that returns a malloc()'ed string * * @param path The filepath to be inspected * @retval (char*)[NULL, char*] Returns a null-terminated string on success, or `null` on error */ char * vxdirname(const char * const path) { char *tmp = NULL; if(!path) { // Path being null is a special case which should return early, before anything else (as to avoid null dereference) tmp = strdup("."); if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, " could not strdup \".\" for set path result \"NULL\"", ); return tmp; } const char * const special[] = {"..", ".", "/"}; for(int i = 0; i < STATIC_ARRAY_LEN(special); i++) { if(strncmp(path, special[i], strlen(special[i])) == 0) { tmp = strdup(special[i]); if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, " could not strdup a set path result", ); return tmp; } } /* From the manpages: (man 3 dirname) // +=======================================+ // | path dirname basename | // +=======================================+ // | /usr/lib /usr lib | // | /usr/ / usr | // | usr . usr | // +=======================================+ */ // Get a temp copy of the path for manipulation purposes tmp = strdup(path); if(!tmp) { if(___VXGG___VERBOSE_ERRORS___) WARN(errno, " could not strdup the given path \"%s\" for internal manipulation", , path); return NULL; } // If there's a trailing '/', delete it size_t pathlen = strlen(path); if(tmp[pathlen - 1] == '/') { tmp[pathlen - 1] = '\0'; pathlen--; } // Ok, I think the easiest way to do this (if maybe a bit slow) is to count the number of '/'s in the string // If there's only one, return '/' // If there are 2 or more, find the last one in the list and set it to '\0' size_t count = 0; for(size_t i = 0; i < pathlen; i++) { if(tmp[i] == '/') count++; } if(count < 2) { free(tmp); if(count == 1) tmp = strdup("/"); else tmp = strdup("."); if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, " Error: Could not strdup \"%s\" for set path result", , ((count == 0) ? "." : "/")); return tmp; } for(size_t i = 0, c2 = 0; i < pathlen; i++) { if(tmp[i] == '/') c2++; if(c2 == count) tmp[i] = '\0'; } char * const actual = strdup(tmp); free(tmp); if(!actual && ___VXGG___VERBOSE_ERRORS___) WARN(errno, " could not strdup tmp string to make a shorter end string", ); return actual; } #endif