diff --git a/include/dusk/string.hpp b/include/dusk/string.hpp index f1a365ebbb..598ae83730 100644 --- a/include/dusk/string.hpp +++ b/include/dusk/string.hpp @@ -7,6 +7,17 @@ namespace dusk { +inline void strncpyProxy(char* dst, const char* src, size_t count) { +#if _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) +#endif + strncpy(dst, src, count); +#if _MSC_VER +#pragma warning(pop) +#endif +} + /** * Copy a string to a fixed-size array. * Truncates if the destination is not large enough, always inserts a null terminator (padding the remainder of the buffer with zeroes.) @@ -15,13 +26,8 @@ template void SafeStringCopyTruncate(char (&buffer)[BufSize], const char* src) { static_assert(BufSize > 0, "Target buffer cannot be size zero"); - // Can't just use strncpy as I can't figure out how to selectively mute the warnings on MSVC. - // And can't use strncpy_s on MSVC as it doesn't fill the entire buffer. - constexpr size_t copyBufSize = BufSize - 1; - const auto srcLen = strlen(src); - const auto copyLen = srcLen > copyBufSize ? copyBufSize : srcLen; - memcpy(buffer, src, copyLen); - memset(buffer + copyLen, 0, BufSize - copyLen); + strncpyProxy(buffer, src, BufSize); + buffer[BufSize - 1] = 0; } /** @@ -35,16 +41,12 @@ void SafeStringCopy(char (&buffer)[BufSize], const char* src) { CRASH("Cannot copy string to same buffer"); } - // Can't just use strncpy as I can't figure out how to selectively mute the warnings on MSVC. - // And can't use strncpy_s on MSVC as it doesn't fill the entire buffer. - constexpr size_t copyBufSize = BufSize - 1; - const auto srcLen = strlen(src); - if (srcLen > copyBufSize) { + if (strlen(src) > BufSize - 1) { CRASH("Destination buffer too small!"); } - memcpy(buffer, src, srcLen); - memset(buffer + srcLen, 0, BufSize - srcLen); + strncpyProxy(buffer, src, BufSize); + buffer[BufSize - 1] = 0; } }