From c415e2ca8ff51f41984ace8fe796187e6ad0fa27 Mon Sep 17 00:00:00 2001 From: Timerix Date: Tue, 12 Aug 2025 19:51:07 +0300 Subject: [PATCH] str_trim --- include/tlibc/errors.h | 2 +- include/tlibc/string/str.h | 3 +++ src/errors.c | 6 +++--- src/string/str.c | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 4 deletions(-) diff --git a/include/tlibc/errors.h b/include/tlibc/errors.h index c736bb7..b323c82 100755 --- a/include/tlibc/errors.h +++ b/include/tlibc/errors.h @@ -22,7 +22,7 @@ typedef struct Error { } Error; Error* Error_create(const char* msg, bool is_msg_on_heap, ErrorCallPos p); -void Error_destroy(Error* e); +void Error_free(Error* e); void Error_addCallPos(Error* e, ErrorCallPos p); str Error_toStr(Error* e); void Error_printAndExit(Error* e) __attribute__ ((__noreturn__)); diff --git a/include/tlibc/string/str.h b/include/tlibc/string/str.h index 4c3b4e7..509b03f 100755 --- a/include/tlibc/string/str.h +++ b/include/tlibc/string/str.h @@ -48,3 +48,6 @@ str str_toUpper(str src); str str_toLower(str src); str hex_to_str(Array(u8) buf, bool uppercase); + +/// @brief removes blank characters from start and end of the line +void str_trim(str* line, bool set_zero_at_end); diff --git a/src/errors.c b/src/errors.c index d9bffb2..72ec4a3 100755 --- a/src/errors.c +++ b/src/errors.c @@ -12,10 +12,11 @@ Error* Error_create(const char* msg, bool is_msg_on_heap, ErrorCallPos p){ return e; } -void Error_destroy(Error* e){ +void Error_free(Error* e){ if(e->is_msg_on_heap) free(e->msg.data); free(e->call_stack.data); + free(e); } void Error_addCallPos(Error* e, ErrorCallPos p){ @@ -47,7 +48,6 @@ void Error_printAndExit(Error* e){ str e_str = Error_toStr(e); printfe("%s\n", e_str.data); free(e_str.data); - Error_destroy(e); - free(e); + Error_free(e); exit(111); } diff --git a/src/string/str.c b/src/string/str.c index f95b656..84f74c4 100755 --- a/src/string/str.c +++ b/src/string/str.c @@ -132,3 +132,39 @@ str hex_to_str(Array(u8) buf, bool uppercase){ StringBuilder_append_memory(&sb, buf, uppercase); return StringBuilder_getStr(&sb); } + +void str_trim(str* line, bool set_zero_at_end){ + bool stop = false; + // loop forward + while(line->size > 0 && !stop){ + char first_char = line->data[line->size - 1]; + switch(first_char){ + case '\0': case '\r': case '\n': + case '\t': case ' ': + line->data++; + line->size--; + break; + default: + stop = true; + break; + } + } + // loop backward + while(line->size > 0 && !stop) + { + char last_char = line->data[line->size - 1]; + switch(last_char){ + case '\0': case '\r': case '\n': + case '\t': case ' ': + line->size--; + break; + default: + stop = true; + break; + } + } + if(set_zero_at_end){ + line->data[line->size] = '\0'; + line->isZeroTerminated = true; + } +}