From 0b64a137dfae755ef543cc0248783306a4893cd6 Mon Sep 17 00:00:00 2001 From: Lixin Wei Date: Sun, 13 Jul 2025 16:15:49 +0800 Subject: [PATCH] Extend rfl::AllowRawPtrs to std::string_view --- include/rfl/parsing/Parser_string_view.hpp | 25 ++++++++++++++++------ tests/json/test_pointer_fields.cpp | 9 ++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/include/rfl/parsing/Parser_string_view.hpp b/include/rfl/parsing/Parser_string_view.hpp index c507bb18..641c1701 100644 --- a/include/rfl/parsing/Parser_string_view.hpp +++ b/include/rfl/parsing/Parser_string_view.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_STRING_VIEW_HPP_ #define RFL_PARSING_PARSER_STRING_VIEW_HPP_ +#include #include #include #include @@ -19,12 +20,24 @@ template struct Parser { using InputVarType = typename R::InputVarType; - static Result read(const R&, const InputVarType&) noexcept { - static_assert(always_false_v, - "Reading into std::string_view is dangerous and " - "therefore unsupported. " - "Please consider using std::string instead."); - return error("Unsupported."); + static Result read(const R& _r, + const InputVarType& _var) noexcept { + if constexpr (!ProcessorsType::allow_raw_ptrs_) { + static_assert(always_false_v, + "Reading into std::string_view is dangerous and " + "therefore unsupported. " + "Please consider using std::string instead, or use the " + "rfl::AllowRawPtrs processor."); + return error("Unsupported."); + } else { + return Parser::read(_r, _var) + .transform([](std::string&& str) { + char* data = + new char[str.size() + 1]; // +1 for the null terminator + std::memcpy(data, str.data(), str.size() + 1); + return std::string_view(data, str.size()); + }); + } } template diff --git a/tests/json/test_pointer_fields.cpp b/tests/json/test_pointer_fields.cpp index de1461b9..68b0584a 100644 --- a/tests/json/test_pointer_fields.cpp +++ b/tests/json/test_pointer_fields.cpp @@ -40,5 +40,14 @@ TEST(json, test_pointer_fields) { delete homer.children; delete homer2.children; + + // test string_view + const std::string_view str = "wa oh what a coincidence"; + const auto json_str_view = rfl::json::write(str); + const auto str_view_back = + rfl::json::read(json_str_view) + .value(); + EXPECT_EQ(str, str_view_back); + delete str_view_back.data(); } } // namespace test_pointer_fields