From 8e245a6c9a8287178b2d0853dec24f442c52ce95 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Fri, 27 Jun 2025 09:27:53 -0700 Subject: Remove bsd string dependency --- cstring/include/cstring.h | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) (limited to 'cstring/include/cstring.h') diff --git a/cstring/include/cstring.h b/cstring/include/cstring.h index 8ed4e93..3e693e1 100644 --- a/cstring/include/cstring.h +++ b/cstring/include/cstring.h @@ -3,14 +3,23 @@ #include -#ifdef __linux__ -#include -#else -#include -#endif #include #include #include +#include + +// ----------------------------------------------------------------------------- +// C-string helpers. + +/// Return a hash of the given string. +uint64_t cstring_hash(const char* str); + +/// Copy 'count' characters from the source to the destination, null-terminating +/// the destination. +static inline void cstring_copy(char* dst, const char* src, size_t count) { + memcpy(dst, src, count * sizeof(char)); + dst[count] = '\0'; +} // ----------------------------------------------------------------------------- // Fix-sized strings. @@ -38,7 +47,8 @@ return (STRING){0}; \ } else { \ STRING str = (STRING){0}; \ - str.length = strlcpy(str.str, cstr, SIZE); \ + str.length = strlen(cstr); \ + cstring_copy(str.str, cstr, str.length); \ return str; \ } \ } \ @@ -65,7 +75,7 @@ static inline void STRING##_append_cstr_len( \ STRING* a, const char* b, const size_t b_length) { \ ASSERT(a->length + b_length + 1 <= SIZE); \ - strlcpy(a->str + a->length, b, SIZE - a->length); \ + cstring_copy(a->str + a->length, b, SIZE - a->length); \ a->length += b_length; \ } \ \ @@ -103,7 +113,7 @@ ASSERT(start < a.length); \ ASSERT(end <= a.length); \ STRING str = {0}; \ - strlcpy(str.str, &a.str[start], end - start); \ + cstring_copy(str.str, &a.str[start], end - start); \ return str; \ } \ \ @@ -134,15 +144,6 @@ return cstring_hash(str.str); \ } -/// Return a hash of the given string. -static inline uint64_t cstring_hash(const char* str) { - uint64_t hash = 0; - for (size_t i = 0; i < strlen(str); ++i) { - hash = (uint64_t)str[i] + (hash << 6) + (hash << 16) - hash; - } - return hash; -} - DEF_STRING(sstring, 32) // Small. DEF_STRING(mstring, 256) // Medium. DEF_STRING(lstring, 1024) // Large. -- cgit v1.2.3