From 90d90f334d1b64753ec72a524fce1c5f8e9e4d31 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Fri, 12 Sep 2025 07:27:09 -0700 Subject: [PATCH] [wpiutil] Add alloc_wpi_string() and copy_wpi_string() (#8222) These are useful to allocate a WPI_String, rather than referencing existing data. --- wpiutil/src/main/native/include/wpi/string.h | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/wpiutil/src/main/native/include/wpi/string.h b/wpiutil/src/main/native/include/wpi/string.h index b84fdd439c..151c9f6c93 100644 --- a/wpiutil/src/main/native/include/wpi/string.h +++ b/wpiutil/src/main/native/include/wpi/string.h @@ -5,6 +5,7 @@ #pragma once #ifdef __cplusplus +#include #include #endif @@ -106,3 +107,24 @@ void WPI_FreeStringArray(const struct WPI_String* wpiStringArray, #ifdef __cplusplus } // extern "C" #endif // __cplusplus + +#ifdef __cplusplus +namespace wpi { + +/** Allocates a copy of a string_view and stores the result into a WPI_String */ +inline WPI_String alloc_wpi_string(std::string_view view) { + WPI_String out; + size_t len = view.size(); + std::memcpy(WPI_AllocateString(&out, len), view.data(), len); + return out; +} + +/** Allocates a copy of a WPI_String */ +inline WPI_String copy_wpi_string(const WPI_String& str) { + if (str.str == nullptr || str.len == 0) { + return WPI_String{nullptr, 0}; + } + return alloc_wpi_string(to_string_view(&str)); +} +} // namespace wpi +#endif