util.h 1.5 KiB raw
1
#ifndef UTIL_H
2
#define UTIL_H
3
4
#include <stdlib.h>
5
#include <string.h>
6
7
#include "types.h"
8
9
/**
10
 * Concatenate string src to the end of dst.
11
 */
12
static inline usize strlcat(char *dst, const char *src, usize dsize) {
13
    usize dst_len = strlen(dst);
14
    usize src_len = strlen(src);
15
16
    /* If destination buffer is already full or too small, can't append */
17
    if (dst_len >= dsize) {
18
        return dst_len + src_len; /* Return what length would be */
19
    }
20
21
    /* Calculate remaining space in destination */
22
    usize remaining = dsize - dst_len - 1; /* -1 for null terminator */
23
24
    if (remaining > 0) {
25
        /* Use strncat to append, but limit to remaining space */
26
        strncat(dst, src, remaining);
27
    }
28
    /* Return total length that would be created */
29
    return dst_len + src_len;
30
}
31
32
/* Copy a string safely */
33
static inline void strndup(char *dst, const char *src, size_t maxlen) {
34
    if (!dst || !src)
35
        return;
36
37
    size_t srclen  = strlen(src);
38
    size_t copylen = srclen < maxlen - 1 ? srclen : maxlen - 1;
39
40
    memcpy(dst, src, copylen);
41
    dst[copylen] = '\0';
42
}
43
44
/* Like `strstr` but find the _last_ occurrence. */
45
static inline char *strrstr(const char *haystack, const char *needle) {
46
    if (*needle == '\0') {
47
        return (char *)haystack + strlen(haystack);
48
    }
49
    char *result = NULL;
50
    char *p      = strstr(haystack, needle);
51
52
    while (p != NULL) {
53
        result = p;
54
        p      = strstr(p + 1, needle);
55
    }
56
    return result;
57
}
58
59
#endif