summaryrefslogtreecommitdiffstats
path: root/src/util.c
blob: a2c6c18bf9466baf9dd3cdb5d2b7e43770d1fb22 (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
#include "internal.h"

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

void cepis_buf_init(cepis_buf_t *buf)
{
        buf->data = NULL;
        buf->len = 0;
        buf->cap = 0;
}

bool cepis_buf_append(cepis_buf_t *buf, const char *data, size_t len)
{
        if (buf->len + len + 1 > buf->cap) {
                size_t cap = buf->cap ? buf->cap : 256;
                char *grown;
                while (buf->len + len + 1 > cap) {
                        if (cap > (size_t)-1 / 2)
                                return false;
                        cap *= 2;
                }
                grown = realloc(buf->data, cap);
                if (grown == NULL)
                        return false;
                buf->data = grown;
                buf->cap = cap;
        }
        if (len > 0)
                memcpy(buf->data + buf->len, data, len);
        buf->len += len;
        buf->data[buf->len] = '\0';
        return true;
}

bool cepis_buf_append_str(cepis_buf_t *buf, const char *text)
{
        return cepis_buf_append(buf, text, strlen(text));
}

void cepis_buf_free(cepis_buf_t *buf)
{
        free(buf->data);
        cepis_buf_init(buf);
}

char *cepis_strdup(const char *text)
{
        size_t len;
        char *copy;

        if (text == NULL)
                text = "";
        len = strlen(text);
        copy = malloc(len + 1);
        if (copy == NULL)
                return NULL;
        memcpy(copy, text, len + 1);
        return copy;
}

cepis_status_t cepis_set_error(cepis_error_t *err, cepis_status_t status,
                               long http_status, double retry_after,
                               const char *fmt, ...)
{
        va_list args;

        if (err == NULL)
                return status;
        err->status = status;
        err->http_status = http_status;
        err->retry_after = retry_after;
        va_start(args, fmt);
        vsnprintf(err->message, sizeof(err->message), fmt, args);
        va_end(args);
        return status;
}