Add a regular strlcpy implementation

That also works for buffers without a compile time known size.
This commit is contained in:
Robbert van der Helm
2022-09-23 20:51:20 +02:00
parent e0c260ba23
commit 5732b45769
2 changed files with 20 additions and 0 deletions
+13
View File
@@ -94,6 +94,19 @@ bool is_watchdog_timer_disabled() {
return disable_watchdog_env && disable_watchdog_env == "1"sv;
}
size_t strlcpy_buffer(char* dst, const std::string& src, size_t size) {
if (size == 0) {
return src.size();
}
// Make sure there's always room for a null terminator
const size_t copy_len = std::min(size - 1, src.size());
std::copy(src.c_str(), src.c_str() + copy_len, dst);
dst[copy_len] = 0;
return src.size();
}
ScopedFlushToZero::ScopedFlushToZero() noexcept {
old_ftz_mode_ = _MM_GET_FLUSH_ZERO_MODE();
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
+7
View File
@@ -159,6 +159,13 @@ size_t strlcpy_buffer(char dst[N], const std::string& src) {
return src.size();
}
/**
* An implementation of BSD's `strlcpy()` function specialized for copying C++
* strings to char buffers with runtime known lengths.
* https://linux.die.net/man/3/strlcpy
*/
size_t strlcpy_buffer(char* dst, const std::string& src, size_t size);
/**
* A RAII wrapper that will temporarily enable the FTZ flag so that denormals
* are automatically flushed to zero, returning to whatever the flag was