From 396751d22cc7ce7c2c0477eca5a3248602c6585e Mon Sep 17 00:00:00 2001 From: lixianjing Date: Tue, 1 Oct 2024 18:00:12 +0800 Subject: [PATCH] improve str utils functions --- src/tkc/utils.c | 28 ++++++++++++---------------- tests/utils_test.cc | 3 +++ 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/tkc/utils.c b/src/tkc/utils.c index 6f2565bf6..446d43bca 100644 --- a/src/tkc/utils.c +++ b/src/tkc/utils.c @@ -335,9 +335,12 @@ const char* tk_ftoa(char* str, int len, double value) { } char* tk_strcpy(char* dst, const char* src) { + return tk_strncpy(dst, src, tk_strlen(src)); +} + +char* tk_strncpy(char* dst, const char* src, size_t len) { return_value_if_fail(dst != NULL && src != NULL, NULL); if (dst != src) { - uint32_t len = tk_strlen(src); memmove(dst, src, len); dst[len] = '\0'; return dst; @@ -346,17 +349,6 @@ char* tk_strcpy(char* dst, const char* src) { } } -char* tk_strncpy(char* dst, const char* src, size_t len) { - return_value_if_fail(dst != NULL && src != NULL, NULL); - - if (dst != src) { - strncpy(dst, src, len); - dst[len] = '\0'; - } - - return dst; -} - char* tk_strncpy_s(char* dst, size_t dst_len, const char* src, size_t src_len) { size_t len = 0; return_value_if_fail(dst != NULL && src != NULL && dst_len > 0, NULL); @@ -707,10 +699,14 @@ char* tk_str_copy(char* dst, const char* src) { if (src != NULL) { uint32_t size = tk_strlen(src) + 1; if (dst != NULL) { - char* str = TKMEM_REALLOCT(char, dst, size); - return_value_if_fail(str != NULL, dst); - memmove(str, src, size); - dst = str; + if (dst <= src && src <= dst + tk_strlen(dst)) { + tk_strncpy(dst, src, size - 1); + } else { + char* str = TKMEM_REALLOCT(char, dst, size); + return_value_if_fail(str != NULL, dst); + memcpy(str, src, size); + dst = str; + } } else { char* str = tk_strndup(src, size - 1); return_value_if_fail(str != NULL, dst); diff --git a/tests/utils_test.cc b/tests/utils_test.cc index a49e28adb..a3000d93f 100644 --- a/tests/utils_test.cc +++ b/tests/utils_test.cc @@ -347,6 +347,9 @@ TEST(Utils, tk_strcpy) { tk_strcpy(str, str + 3); ASSERT_STREQ(str, "123"); + + tk_strncpy(str + 2, str, 3); + ASSERT_STREQ(str, "12123"); } TEST(Utils, tk_str_copy) {