[wpiutil] Add alloc_wpi_string() and copy_wpi_string() (#8222)

These are useful to allocate a WPI_String, rather than referencing existing data.
This commit is contained in:
Peter Johnson
2025-09-12 07:27:09 -07:00
committed by GitHub
parent 909f8a1dc4
commit 90d90f334d

View File

@@ -5,6 +5,7 @@
#pragma once
#ifdef __cplusplus
#include <cstring>
#include <string_view>
#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