summaryrefslogtreecommitdiffstats
path: root/src/util.c
blob: a7513b3cd03368e8efca1b998afafdf656720a27 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/* util.c - allocation that stops rather than limps, and a name for messages.
 *
 * A hook that cannot allocate is not in a position to decide anything, so
 * these exit with the policy-unavailable status rather than returning NULL
 * somewhere the caller forgot to look. */
#include "authz.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *progname = "git-authz";

static void oom(void)
{
    fprintf(stderr, "%s: out of memory\n", progname);
    exit(3);
}

void sb_init(strbuf_t *b)
{
    b->cap = 64;
    b->len = 0;
    b->s = xmalloc(b->cap);
    b->s[0] = '\0';
}

static void sb_room(strbuf_t *b, size_t extra)
{
    if (b->len + extra + 1 <= b->cap)
        return;
    while (b->len + extra + 1 > b->cap)
        b->cap *= 2;
    b->s = xrealloc(b->s, b->cap);
}

void sb_add(strbuf_t *b, const char *s)
{
    size_t n;

    if (s == NULL)
        return;
    n = strlen(s);
    sb_room(b, n);
    memcpy(b->s + b->len, s, n + 1);
    b->len += n;
}

void sb_addf(strbuf_t *b, const char *fmt, ...)
{
    va_list ap;
    int n;
    char *out;

    va_start(ap, fmt);
    n = vsnprintf(NULL, 0, fmt, ap);
    va_end(ap);
    if (n < 0)
        return;
    sb_room(b, (size_t)n);
    va_start(ap, fmt);
    out = b->s + b->len;
    n = vsnprintf(out, b->cap - b->len, fmt, ap);
    va_end(ap);
    if (n < 0) {
        b->s[b->len] = '\0';
        return;
    }
    b->len += (size_t)n;
}

void sb_free(strbuf_t *b)
{
    free(b->s);
    b->s = NULL;
    b->len = b->cap = 0;
}

void *xmalloc(size_t n)
{
    void *p = malloc(n != 0 ? n : 1);

    if (p == NULL)
        oom();
    return p;
}

void *xrealloc(void *ptr, size_t n)
{
    void *p = realloc(ptr, n != 0 ? n : 1);

    if (p == NULL)
        oom();
    return p;
}

char *xstrdup(const char *s)
{
    size_t n;
    char *p;

    if (s == NULL)
        return NULL;
    n = strlen(s) + 1;
    p = xmalloc(n);
    memcpy(p, s, n);
    return p;
}

char *xsubstr(const char *s, size_t len)
{
    char *p = xmalloc(len + 1);

    memcpy(p, s, len);
    p[len] = '\0';
    return p;
}