#ifndef UTIL_H #define UTIL_H #include #include #include "types.h" /** * Concatenate string src to the end of dst. */ static inline usize strlcat(char *dst, const char *src, usize dsize) { usize dst_len = strlen(dst); usize src_len = strlen(src); /* If destination buffer is already full or too small, can't append */ if (dst_len >= dsize) { return dst_len + src_len; /* Return what length would be */ } /* Calculate remaining space in destination */ usize remaining = dsize - dst_len - 1; /* -1 for null terminator */ if (remaining > 0) { /* Use strncat to append, but limit to remaining space */ strncat(dst, src, remaining); } /* Return total length that would be created */ return dst_len + src_len; } /* Copy a string safely */ static inline void strndup(char *dst, const char *src, size_t maxlen) { if (!dst || !src) return; size_t srclen = strlen(src); size_t copylen = srclen < maxlen - 1 ? srclen : maxlen - 1; memcpy(dst, src, copylen); dst[copylen] = '\0'; } /* Like `strstr` but find the _last_ occurrence. */ static inline char *strrstr(const char *haystack, const char *needle) { if (*needle == '\0') { return (char *)haystack + strlen(haystack); } char *result = NULL; char *p = strstr(haystack, needle); while (p != NULL) { result = p; p = strstr(p + 1, needle); } return result; } #endif