From 743b896bfdac28d8dda8ffdf8ffa427e09696ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Branimir=20Karad=C5=BEi=C4=87?= Date: Tue, 29 Nov 2016 22:34:13 -0800 Subject: [PATCH] Added strlncpy. --- include/bx/string.h | 17 +++++++++++++++++ tests/string_test.cpp | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/include/bx/string.h b/include/bx/string.h index 5913043..655529a 100644 --- a/include/bx/string.h +++ b/include/bx/string.h @@ -48,6 +48,23 @@ namespace bx return ptr - _str; } + /// Copy _num characters from string _src to _dst buffer of maximum _dstSize capacity + /// including zero terminator. Copy will be terminated with '\0'. + inline size_t strlncpy(char* _dst, size_t _dstSize, const char* _src, size_t _num = -1) + { + BX_CHECK(NULL != _dst, "_dst can't be NULL!"); + BX_CHECK(NULL != _src, "_src can't be NULL!"); + BX_CHECK(0 < _dstSize, "_dstSize can't be 0!"); + + const size_t len = strnlen(_src, _num); + const size_t max = _dstSize-1; + const size_t num = (len < max ? len : max); + strncpy(_dst, _src, num); + _dst[num] = '\0'; + + return num; + } + /// Find substring in string. Limit search to _size. inline const char* strnstr(const char* _str, const char* _find, size_t _size) { diff --git a/tests/string_test.cpp b/tests/string_test.cpp index 3d98e38..e68a04a 100644 --- a/tests/string_test.cpp +++ b/tests/string_test.cpp @@ -19,6 +19,27 @@ TEST_CASE("strnlen", "") REQUIRE(4 == bx::strnlen(test, UINT32_MAX) ); } +TEST_CASE("strlncpy", "") +{ + char dst[128]; + size_t num; + + num = bx::strlncpy(dst, 1, "blah"); + REQUIRE(num == 0); + + num = bx::strlncpy(dst, 3, "blah", 3); + REQUIRE(0 == strcmp(dst, "bl") ); + REQUIRE(num == 2); + + num = bx::strlncpy(dst, sizeof(dst), "blah", 3); + REQUIRE(0 == strcmp(dst, "bla") ); + REQUIRE(num == 3); + + num = bx::strlncpy(dst, sizeof(dst), "blah"); + REQUIRE(0 == strcmp(dst, "blah") ); + REQUIRE(num == 4); +} + TEST_CASE("StringView", "") { bx::StringView sv("test");