Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions include/rfl/parsing/Parser_string_view.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef RFL_PARSING_PARSER_STRING_VIEW_HPP_
#define RFL_PARSING_PARSER_STRING_VIEW_HPP_

#include <cstring>
#include <map>
#include <string>
#include <string_view>
Expand All @@ -19,12 +20,24 @@ template <class R, class W, class ProcessorsType>
struct Parser<R, W, std::string_view, ProcessorsType> {
using InputVarType = typename R::InputVarType;

static Result<std::string_view> read(const R&, const InputVarType&) noexcept {
static_assert(always_false_v<R>,
"Reading into std::string_view is dangerous and "
"therefore unsupported. "
"Please consider using std::string instead.");
return error("Unsupported.");
static Result<std::string_view> read(const R& _r,
const InputVarType& _var) noexcept {
if constexpr (!ProcessorsType::allow_raw_ptrs_) {
static_assert(always_false_v<R>,
"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<R, W, std::string, ProcessorsType>::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());
Comment thread
lixin-wei marked this conversation as resolved.
});
}
}

template <class P>
Expand Down
9 changes: 9 additions & 0 deletions tests/json/test_pointer_fields.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string_view, rfl::AllowRawPtrs>(json_str_view)
.value();
EXPECT_EQ(str, str_view_back);
Comment thread
lixin-wei marked this conversation as resolved.
delete str_view_back.data();
}
} // namespace test_pointer_fields
Loading