summaryrefslogtreecommitdiff
path: root/src/shared.c
blob: 2f6dd5b0aae5cb0cd5f8d76dac7289c76af649ed (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
63
64
65
66
67
68
69
70
71
72
73
74
#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;
}

#if !defined _GNU_SOURCE

int vasprintf(char **str, const char *format, va_list ap) {
    va_list ap2;
    int length, ret;

    va_copy(ap2, ap);
    if((length = vsnprintf(NULL, 0, format, ap2)) < 0)
        return -1;
    length++; // + 1 because sprintf does not count the null byte
    va_end(ap2);

    char *temp = reallocarray(*str, length, sizeof(char));
    if(temp == NULL)
        return -1;

    if((ret = vsnprintf(temp, length, format, ap)) < 0) {
        free(temp);
        return -1;
    } else {
        *str = temp;
    }
    
    return ret;
}

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

    va_start(ap, format);
    int ret = vasprintf(str, format, ap);
    va_end(ap);
    
    return ret;
}

#endif