This commit is contained in:
2025-04-07 17:57:06 -05:00
parent 7a3d7a5868
commit a779da6c72
98 changed files with 655 additions and 8974 deletions

85
src/util/string.c Normal file
View File

@@ -0,0 +1,85 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "string.h"
#include "assert/assert.h"
#include "util/memory.h"
bool_t stringIsWhitespace(const char_t c) {
return isspace(c);
}
void stringCopy(char_t *dest, const char_t *src, const size_t destSize) {
assertNotNull(dest, "dest must not be NULL");
assertNotNull(src, "src must not be NULL");
assertTrue(destSize > 0, "destSize must be greater than 0");
assertStrLenMax(src, destSize, "src is too long");
memoryCopy(dest, src, strlen(src) + 1);
}
int stringCompare(const char_t *str1, const char_t *str2) {
assertNotNull(str1, "str1 must not be NULL");
assertNotNull(str2, "str2 must not be NULL");
return strcmp(str1, str2);
}
void stringTrim(char_t *str) {
assertNotNull(str, "str must not be NULL");
// Trim leading whitespace
char_t *start = str;
while(stringIsWhitespace(*start)) start++;
// Trim trailing whitespace
char_t *end = start + strlen(start) - 1;
while (end >= start && stringIsWhitespace(*end)) end--;
// Null-terminate the string
*(end + 1) = '\0';
// Move trimmed string to the original buffer
if (start != str) memmove(str, start, end - start + 2);
}
char_t * stringToken(char_t *str, const char_t *delim) {
assertNotNull(str, "str must not be NULL");
assertNotNull(delim, "delim must not be NULL");
return strtok(str, delim);
}
int32_t stringFormat(
char_t *dest,
const size_t destSize,
char_t *format,
...
) {
assertNotNull(dest, "dest must not be NULL");
assertNotNull(format, "format must not be NULL");
assertTrue(destSize > 0, "destSize must be greater than 0");
va_list args;
va_start(args, format);
int32_t result = stringFormatVA(dest, destSize, format, args);
va_end(args);
return result;
}
int32_t stringFormatVA(
char_t *dest,
const size_t destSize,
char_t *format,
va_list args
) {
assertNotNull(dest, "dest must not be NULL");
assertNotNull(format, "format must not be NULL");
assertTrue(destSize > 0, "destSize must be greater than 0");
int32_t ret = vsnprintf(dest, destSize, format, args);
assertTrue(ret >= 0, "Failed to format string.");
assertTrue(ret < destSize, "Formatted string is too long.");
return ret;
}