Added strlncpy.

This commit is contained in:
Branimir Karadžić
2016-11-29 22:34:13 -08:00
parent 282a2ce91c
commit 743b896bfd
2 changed files with 38 additions and 0 deletions

View File

@@ -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)
{

View File

@@ -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");