summaryrefslogtreecommitdiff
path: root/src/shared.h
blob: af6c56edec92d06517d3da156350ee172ad35ee3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#ifndef __VXGG_REWRITE___SHARED_H___3880294315821___
#define __VXGG_REWRITE___SHARED_H___3880294315821___

#include <stddef.h>

#define STATIC_ARRAY_LEN(arr) (sizeof((arr))/sizeof((arr)[0]))

#define RETURNWERR(errval, retval) do {\
    errno = (errval);\
    return (retval);\
} while (0)

// Defines how `x___alloc()` functions should exit. `___VXGG___XALLOC_EXIT_ON_ERROR___ > 0` calls `error()`, and thus functions
// registered with `atexit()` and `on_exit()`. `___VXGG___XALLOC_EXIT_ON_ERROR___ <= 0` calls `abort()` on error. `x___alloc()` 
// type functions will ALWAYS 'abort', doing otherwise defeats the purpose of the function type
#define ___VXGG___XALLOC_EXIT_ON_ERROR___ 1

// Defines whether vxgg functions that can error print out a short warning of the error when one is encountered. 
// `___VXGG___VERBOSE_ERRORS___ > 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___XALLOC_EXIT_ON_ERROR___)\
        abort();\
    if(!___VXGG___VERBOSE_ERRORS___)\
        exit(EXIT_FAILURE);\
    error(EXIT_FAILURE, errno, (msg)__VA_ARGS__);\
    exit(EXIT_FAILURE); /* Makes gcc happy */\
} while (0)

// `calloc()` with error checking. Calls `error()` or `abort()` on error, depending on the value of `___VXGG___XALLOC_EXIT_ON_ERROR___`
void* xcalloc(size_t nmemb, size_t size);

// `reallocarray()` with error checking. Calls `error()` or `abort()` on error, depending on the value of `___VXGG___XALLOC_EXIT_ON_ERROR___`
void* xreallocarray(void *ptr, size_t nmemb, size_t size);

// Read the entire contents of a file descriptor into a malloc()'ed buffer
int readwholebuffer(char **str, unsigned long int initsize, int fd);

// Write the entire contents of a buffer into a file descriptor
int writewholebuffer(int fd, const unsigned char *buf, int len);

// `dirname()` reimplementation that returns a malloc()'ed string. According to the `x___` naming scheme, exits on alloc error.
// `___VXGG___XALLOC_EXIT_ON_ERROR___` influences whether `exit()` or `abort()` is called on error, and `___VXGG___VERBOSE_ERRORS___`
// influences whether diagnostic error messages are printed
char *xdirname(const char * const path);

#endif