Skip to content

Commit 18feb02

Browse files
authored
Extend rfl::AllowRawPtrs to std::string_view (getml#460)
1 parent c496f14 commit 18feb02

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

include/rfl/parsing/Parser_string_view.hpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#ifndef RFL_PARSING_PARSER_STRING_VIEW_HPP_
22
#define RFL_PARSING_PARSER_STRING_VIEW_HPP_
33

4+
#include <cstring>
45
#include <map>
56
#include <string>
67
#include <string_view>
@@ -19,12 +20,24 @@ template <class R, class W, class ProcessorsType>
1920
struct Parser<R, W, std::string_view, ProcessorsType> {
2021
using InputVarType = typename R::InputVarType;
2122

22-
static Result<std::string_view> read(const R&, const InputVarType&) noexcept {
23-
static_assert(always_false_v<R>,
24-
"Reading into std::string_view is dangerous and "
25-
"therefore unsupported. "
26-
"Please consider using std::string instead.");
27-
return error("Unsupported.");
23+
static Result<std::string_view> read(const R& _r,
24+
const InputVarType& _var) noexcept {
25+
if constexpr (!ProcessorsType::allow_raw_ptrs_) {
26+
static_assert(always_false_v<R>,
27+
"Reading into std::string_view is dangerous and "
28+
"therefore unsupported. "
29+
"Please consider using std::string instead, or use the "
30+
"rfl::AllowRawPtrs processor.");
31+
return error("Unsupported.");
32+
} else {
33+
return Parser<R, W, std::string, ProcessorsType>::read(_r, _var)
34+
.transform([](std::string&& str) {
35+
char* data =
36+
new char[str.size() + 1]; // +1 for the null terminator
37+
std::memcpy(data, str.data(), str.size() + 1);
38+
return std::string_view(data, str.size());
39+
});
40+
}
2841
}
2942

3043
template <class P>

tests/json/test_pointer_fields.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,14 @@ TEST(json, test_pointer_fields) {
4040

4141
delete homer.children;
4242
delete homer2.children;
43+
44+
// test string_view
45+
const std::string_view str = "wa oh what a coincidence";
46+
const auto json_str_view = rfl::json::write(str);
47+
const auto str_view_back =
48+
rfl::json::read<std::string_view, rfl::AllowRawPtrs>(json_str_view)
49+
.value();
50+
EXPECT_EQ(str, str_view_back);
51+
delete str_view_back.data();
4352
}
4453
} // namespace test_pointer_fields

0 commit comments

Comments
 (0)