refactor: string extend method

This commit is contained in:
2025-09-07 22:36:30 +02:00
parent 3e0584d139
commit 16ee246956
17 changed files with 2164 additions and 2123 deletions

View File

@@ -138,7 +138,25 @@ int mcl_string_append(mcl_string_s *string, const char *text) {
} }
int mcl_string_extend(mcl_string_s *destination, mcl_string_s *source) { int mcl_string_extend(mcl_string_s *destination, mcl_string_s *source) {
/* TODO */ if (destination == NULL || source == NULL) {
return -1;
}
size_t need = destination->size + source->size;
if (need > destination->capacity) {
/* Reallocate destination data buffer */
destination->capacity = next_power_two(need);
char *tmp = realloc(destination->data, destination->capacity);
if (tmp == NULL) {
return -1;
}
destination->data = tmp;
}
/* Copy memory from source data buffer */
memcpy(destination->data + destination->size, source->data, source->size);
destination->size = need;
destination->data[destination->size] = '\0';
return 0; return 0;
} }

View File

@@ -105,4 +105,15 @@ void mcl_string_toupper(mcl_string_s *string);
*/ */
void mcl_string_tolower(mcl_string_s *string); void mcl_string_tolower(mcl_string_s *string);
/**
* @brief Find a substring inside a string.
*
* @param string String where to search.
* @param substring Substring to search.
* @return Index of the first occurrence, -1 on failure.
*
* @note TODO
*/
int mcl_string_find(mcl_string_s *string, const char *substring);
#endif /* MYCLIB_STRING_H */ #endif /* MYCLIB_STRING_H */

View File

@@ -22,6 +22,13 @@ void test_str2(void) {
assert(strcmp(mcl_string_cstr(s1), "") == 0); assert(strcmp(mcl_string_cstr(s1), "") == 0);
assert(strcmp(mcl_string_cstr(s2), "HELLO, WORLD!") == 0); assert(strcmp(mcl_string_cstr(s2), "HELLO, WORLD!") == 0);
/* Extend a string */
mcl_string_s *extend_me = mcl_string_new("This string is suuuuuuuuuuuuuuuuuuuuuper extended!", 0);
mcl_string_extend(s1, extend_me);
assert(mcl_string_length(s1) == 50);
assert(mcl_string_capacity(s1) == 64);
mcl_string_free(s1); mcl_string_free(s1);
mcl_string_free(s2); mcl_string_free(s2);
mcl_string_free(extend_me);
} }

View File

@@ -5,6 +5,11 @@
#include <assert.h> #include <assert.h>
#include <stdio.h> #include <stdio.h>
void test_hm1();
void test_q1();
void test_str1();
void test_str2();
int main(void) { int main(void) {
puts("==== [Running Hashmap tests] ===="); puts("==== [Running Hashmap tests] ====");
test_hm1(); test_hm1();