From 5732b457693f8263178a29f56028e0d5f3d30f29 Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Fri, 23 Sep 2022 20:51:20 +0200 Subject: [PATCH] Add a regular strlcpy implementation That also works for buffers without a compile time known size. --- src/common/utils.cpp | 13 +++++++++++++ src/common/utils.h | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/src/common/utils.cpp b/src/common/utils.cpp index b8938338..c98e0d27 100644 --- a/src/common/utils.cpp +++ b/src/common/utils.cpp @@ -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); diff --git a/src/common/utils.h b/src/common/utils.h index 083762df..7648ce7f 100644 --- a/src/common/utils.h +++ b/src/common/utils.h @@ -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