diff --git a/src/base/system.c b/src/base/system.c index 261b1c1b0..20b36dcf8 100644 --- a/src/base/system.c +++ b/src/base/system.c @@ -2318,11 +2318,10 @@ void str_copy(char *dst, const char *src, int dst_size) dst[dst_size-1] = 0; /* assure null termination */ } -void str_num_copy(char *dst, const char *src, int num, int dst_size) +void str_truncate(char *dst, int dst_size, const char *src, int truncation_len) { - int n = num >= dst_size ? dst_size - 1 : num; - strncpy(dst, src, n); - dst[n] = '\0'; + int size = truncation_len >= dst_size ? dst_size : truncation_len + 1; + str_copy(dst, src, size); } int str_length(const char *str) diff --git a/src/base/system.h b/src/base/system.h index a9b1ffd32..e75f49f71 100644 --- a/src/base/system.h +++ b/src/base/system.h @@ -997,20 +997,21 @@ void str_append(char *dst, const char *src, int dst_size); void str_copy(char *dst, const char *src, int dst_size); /* - Function: str_num_copy - Copies first num characters of a string to another. + Function: str_truncate + Truncates a string to a given length. Parameters: dst - Pointer to a buffer that shall receive the string. - src - String to be copied. - num - Number of characters to copy. dst_size - Size of the buffer dst. + str - String to be truncated. + truncation_len - Maximum length of the returned string (not + counting the zero termination). Remarks: - The strings are treated as zero-terminated strings. - Guarantees that dst string will contain zero-termination. */ -void str_num_copy(char *dst, const char *src, int num, int dst_size); +void str_truncate(char *dst, int dst_size, const char *src, int truncation_len); /* Function: str_length diff --git a/src/game/client/components/statboard.cpp b/src/game/client/components/statboard.cpp index de851be83..d95b8becc 100644 --- a/src/game/client/components/statboard.cpp +++ b/src/game/client/components/statboard.cpp @@ -85,7 +85,7 @@ void CStatboard::OnMessage(int MsgType, void *pRawMsg) if(t <= p) return; - str_num_copy(aName, p, t - p, sizeof(aName)); + str_truncate(aName, sizeof(aName), p, t - p); for(int i = 0; i < MAX_CLIENTS; i++) { diff --git a/src/test/str.cpp b/src/test/str.cpp index b3c119b73..9958d118b 100644 --- a/src/test/str.cpp +++ b/src/test/str.cpp @@ -180,16 +180,16 @@ TEST(Str, StrFormat) EXPECT_STREQ(aBuf, "99:"); } -TEST(Str, StrNumCopy) +TEST(Str, StrCopyNum) { const char *foo = "Foobar"; char aBuf[64]; - str_num_copy(aBuf, foo, 1, 3); + str_truncate(aBuf, 3, foo, 1); EXPECT_STREQ(aBuf, "F"); - str_num_copy(aBuf, foo, 2, 3); + str_truncate(aBuf, 3, foo, 2); EXPECT_STREQ(aBuf, "Fo"); - str_num_copy(aBuf, foo, 3, 3); + str_truncate(aBuf, 3, foo, 3); EXPECT_STREQ(aBuf, "Fo"); - str_num_copy(aBuf, foo, 6, sizeof(aBuf)); + str_truncate(aBuf, sizeof(aBuf), foo, 6); EXPECT_STREQ(aBuf, "Foobar"); }