Added support for raw pointers; #218 (#244)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-11-05 00:14:56 +01:00
committed by GitHub
parent 458ca09198
commit 2ef144c041
7 changed files with 156 additions and 8 deletions
+36
View File
@@ -34,6 +34,7 @@ The resulting JSON string looks like this:
reflect-cpp currently supports the following processors:
- `rfl::AddStructName`
- `rfl::AllowRawPtrs`
- `rfl::DefaultIfMissing`
- `rfl::NoExtraFields`
- `rfl::NoFieldNames`
@@ -60,6 +61,41 @@ The resulting JSON string looks like this:
{"type":"Person","first_name":"Homer","last_name":"Simpson","age":45}
```
### `rfl::AllowRawPtrs`
By default, reflect-cpp does not allow *reading into* raw pointers. (*Writing from* raw pointers is never a problem.) This is because reading into raw pointers means that the library will allocate memory that the user then has to manually delete. This can lead to misunderstandings and memory leaks.
You might want to consider using some alternatives, such as `std::unique_ptr`, `rfl::Box`,
`std::shared_ptr`, `rfl::Ref` or `std::optional`. But if you absolutely have to use raw pointers, you can pass `rfl::AllowRawPtrs` to `read`:
```cpp
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::vector<Person>* children;`
};
const auto person =
rfl::json::read<Person, rfl::AllowRawPtrs>(json_str);
```
However, you must keep in mind that it is now **YOUR** responsibility
to clean up. Otherwise, there **WILL** be a memory leak.
```cpp
void delete_raw_pointers(const Person& _person) {
if (!_person.children) {
return;
}
for (const auto& child: _person.children) {
delete_raw_pointers(child);
}
delete _person.children;
}
delete_raw_pointers(person);
```
### `rfl::DefaultIfMissing`
The `rfl::DefaultIfMissing` processor is only relevant for reading data. For writing data, it will make no difference.
+1
View File
@@ -9,6 +9,7 @@
#include "rfl/AddStructName.hpp"
#include "rfl/AllOf.hpp"
#include "rfl/AllowRawPtrs.hpp"
#include "rfl/AnyOf.hpp"
#include "rfl/Attribute.hpp"
#include "rfl/Binary.hpp"
+18
View File
@@ -0,0 +1,18 @@
#ifndef RFL_ALLOWRAWPTRS_HPP_
#define RFL_ALLOWRAWPTRS_HPP_
namespace rfl {
/// This is a "fake" processor - it doesn't do much in itself, but its
/// inclusion instructs the parsers to allow raw pointers.
struct AllowRawPtrs {
public:
template <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};
} // namespace rfl
#endif
+6
View File
@@ -3,6 +3,7 @@
#include <type_traits>
#include "internal/is_allow_raw_ptrs_v.hpp"
#include "internal/is_default_if_missing_v.hpp"
#include "internal/is_no_extra_fields_v.hpp"
#include "internal/is_no_field_names_v.hpp"
@@ -16,6 +17,7 @@ struct Processors;
template <>
struct Processors<> {
static constexpr bool allow_raw_ptrs_ = false;
static constexpr bool all_required_ = false;
static constexpr bool default_if_missing_ = false;
static constexpr bool no_extra_fields_ = false;
@@ -30,6 +32,10 @@ struct Processors<> {
template <class Head, class... Tail>
struct Processors<Head, Tail...> {
static constexpr bool allow_raw_ptrs_ =
std::disjunction_v<internal::is_allow_raw_ptrs<Head>,
internal::is_allow_raw_ptrs<Tail>...>;
static constexpr bool all_required_ =
std::disjunction_v<internal::is_no_optionals<Head>,
internal::is_no_optionals<Tail>...>;
@@ -0,0 +1,29 @@
#ifndef RFL_INTERNAL_ISALLOWRAWPTRS_HPP_
#define RFL_INTERNAL_ISALLOWRAWPTRS_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "../AllowRawPtrs.hpp"
namespace rfl {
namespace internal {
template <class T>
class is_allow_raw_ptrs;
template <class T>
class is_allow_raw_ptrs : public std::false_type {};
template <>
class is_allow_raw_ptrs<AllowRawPtrs> : public std::true_type {};
template <class T>
constexpr bool is_allow_raw_ptrs_v =
is_allow_raw_ptrs<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;
} // namespace internal
} // namespace rfl
#endif
+22 -8
View File
@@ -22,14 +22,28 @@ struct Parser<R, W, T*, ProcessorsType> {
using ParentType = Parent<W>;
/// Expresses the variables as type T.
static Result<T*> read(const R&, const InputVarType&) noexcept {
static_assert(always_false_v<T>,
"Reading into raw pointers is dangerous and "
"therefore unsupported. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, "
"rfl::Ref or std::optional instead.");
return Error("Unsupported.");
static Result<T*> read(const R& _r, const InputVarType& _var) noexcept {
if constexpr (!ProcessorsType::allow_raw_ptrs_) {
static_assert(
always_false_v<T>,
"Reading into raw pointers is dangerous and "
"therefore unsupported by default. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, "
"rfl::Ref or std::optional instead. "
"If you absolutely must use raw pointers, "
"you can pass the rfl::AllowRawPtrs processor. "
"Please note that it is then YOUR responsibility "
"to delete the allocated memory. Please also refer "
"to the related documentation (in the section on processors).");
return Error("Unsupported.");
} else {
if (_r.is_empty(_var)) {
return nullptr;
}
return Parser<R, W, T, ProcessorsType>::read(_r, _var).transform(
[](T&& _t) { return new T(std::move(_t)); });
}
}
template <class P>
+44
View File
@@ -0,0 +1,44 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_pointer_fields {
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::vector<Person>* children;
};
TEST(json, test_pointer_fields) {
const auto bart = Person{.first_name = "Bart", .children = nullptr};
const auto lisa = Person{.first_name = "Lisa", .children = nullptr};
const auto maggie = Person{.first_name = "Maggie", .children = nullptr};
const auto homer =
Person{.first_name = "Homer",
.children = new std::vector<Person>({bart, lisa, maggie})};
const std::string expected =
R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson","children":null},{"firstName":"Lisa","lastName":"Simpson","children":null},{"firstName":"Maggie","lastName":"Simpson","children":null}]})";
const auto json_str = rfl::json::write(homer);
EXPECT_EQ(json_str, expected);
const auto homer2 =
rfl::json::read<Person, rfl::AllowRawPtrs>(json_str).value();
const auto json_str2 = rfl::json::write(homer2);
EXPECT_EQ(json_str2, expected);
delete homer.children;
delete homer2.children;
}
} // namespace test_pointer_fields