summaryrefslogtreecommitdiff
path: root/src/shared.c
blob: 0c7c8e24dbce7e95fe0aaeb9b357792bdbfd5fef (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
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "shared.h"

#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <error.h>
#include <stdio.h>

void* xcalloc(size_t nmemb, size_t size) {
    void *mem = calloc(nmemb, size);

    if(mem == NULL) {
        #if defined ___VXGG___XCALLOC_EXIT_ON_ERROR___ && ___VXGG___XCALLOC_EXIT_ON_ERROR___ > 0
            error(1, errno, "<xcalloc> Could not allocate memory");
        #endif

        abort();
    }
    

    return mem;
}

void* xreallocarray(void *ptr, size_t nmemb, size_t size) {
    void *mem = reallocarray(ptr, nmemb, size);
    if(mem == NULL) {
        #if defined ___VXGG___XCALLOC_EXIT_ON_ERROR___ && ___VXGG___XCALLOC_EXIT_ON_ERROR___ > 0
            error(1, errno, "<xreallocarray> Could not allocate memory");

        #endif

        abort();
    }

    return mem;
}

int vsaprintf(char **str, const char *format, va_list ap) {
    va_list ap2;
    va_copy(ap2, ap);

    int length = vsnprintf(NULL, 0, format, ap2) + 1; // + 1 because sprintf does not count the null byte
    char *temp = reallocarray(*str, length, sizeof(char));
    if(temp == NULL)
        return -1;

    int ret = vsnprintf(temp, length, format, ap);
    *str = temp;

    va_end(ap2);
    return ret;
}

int saprintf(char **str, const char *format, ...) {
    va_list ap;
    va_start(ap, format);

    int ret = vsaprintf(str, format, ap);

    va_end(ap);
    return ret;
}