File: custom_parser.md

package info (click to toggle)
reflect-cpp 0.21.0%2Bds-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,140 kB
  • sloc: cpp: 50,336; python: 139; makefile: 29; sh: 3
file content (227 lines) | stat: -rw-r--r-- 7,203 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# Custom parsers

## `rfl::Reflector`

If you absolutely do not want to (or are unable to) make any changes to your
original classes whatsoever, you can create a Reflector template specialization
for your type:

```cpp
namespace rfl {
template <>
struct Reflector<Person> {
  struct ReflType {
    std::string first_name;
    std::string last_name;
  };

  static Person to(const ReflType& v) noexcept {
    return {v.first_name, v.last_name};
  }

  static ReflType from(const Person& v) {
    return {v.first_name, v.last_name};
  }
};
}
```

One way to help make sure that your `ReflType` is kept up to date with your
original class is to use the `rfl::num_fields<T>` utility to implement a compile-
time assertion to verify that they have the same number of fields. The
`rfl::num_fields<T>` utility can be used even in cases where the original
class is too complex for `reflect-cpp`'s default reflection logic or
`rfl::to_view()` to be able to handle.

```cpp
namespace rfl {
template <>
struct Reflector<Person> {
  struct ReflType {
    std::string first_name;
    std::string last_name;
  };
  static_assert(rfl::num_fields<ReflType> == rfl::num_fields<Person>,
    "ReflType and actual type must have the same number of fields");
  // ...
```

It's also fine to define just the `from` method when the original class is
only written, or `to` when the original class is only read:

```cpp
// This can only be used for writing.
namespace rfl {
template <>
struct Reflector<Person> {
  struct ReflType {
    std::string first_name;
    std::string last_name;
  };

  static ReflType from(const Person& v) {
    return {v.first_name, v.last_name};
  }
};
}
```

Note that the `ReflType` does not have to be a struct. For instance, if you have
a custom type called `MyCustomType` that you want to be serialized as a string,
you can do the following:

```cpp
namespace rfl {
template <>
struct Reflector<MyCustomType> {
  using ReflType = std::string;

  static MyCustomType to(const ReflType& str) noexcept {
    return MyCustomType::from_string(str);
  }

  static ReflType from(const MyCustomType& v) {
    return v.to_string();
  }
};
}
```

## `rfl::parsing::CustomParser`

Alternatively, you can implement a custom parser using `rfl::parsing::CustomParser`.

In order to do so, you must do the following:

You must create a helper struct that *can* be parsed. The helper struct must fulfill the following
conditions:

1) It must contain a static method called `from_class` that takes your original class as an input and returns the helper struct. This method must not throw an exception.
2) (Optional) It must contain a method called `to_class` that transforms the helper struct into your original class. This method may throw an exception, if you want to. If you can directly construct your custom class from the field values in the order they were declared in the helper struct, you do not have to write a `to_class` method.

You can then implement a custom parser for your class like this:

```cpp
namespace rfl::parsing {

template <class ReaderType, class WriterType, class ProcessorsType>
struct Parser<ReaderType, WriterType, YourOriginalClass, ProcessorsType>
    : public CustomParser<ReaderType, WriterType, ProcessorsType, YourOriginalClass,
                          YourHelperStruct> {};

}  // namespace rfl::parsing
```

## Example

Suppose your original class looks like this:

```cpp
struct Person {
    Person(const std::string& _first_name, const std::string& _last_name,
           const int _age)
        : first_name_(_first_name), last_name_(_last_name), age_(_age) {}

    const auto& first_name() const { return first_name_; }

    const auto& last_name() const { return last_name_; }

    auto age() const { return age_; }

   private:
    std::string first_name_;
    std::string last_name_;
    int age_;
};
```

You can then write a helper struct:

```cpp
struct PersonImpl {
    rfl::Rename<"firstName", std::string> first_name;
    rfl::Rename<"lastName", std::string> last_name;
    int age;

    // 1) Static method that takes your original class as an input and
    //    returns the helper struct.
    //    MUST NOT THROW AN EXCEPTION!
    static PersonImpl from_class(const Person& _p) noexcept {
        return PersonImpl{.first_name = _p.first_name(),
                          .last_name = _p.last_name(),
                          .age = _p.age()};
    }

    // 2) Const method called `to_class` that transforms the helper struct
    //    into your original class.
    //    In this case, the `to_class` method is actually optional, because
    //    you can directly create Person from the field values.
    Person to_class() const { return Person(first_name(), last_name(), age); }
};
```

You then implement the custom parser:

```cpp
namespace rfl::parsing {

template <class ReaderType, class WriterType, class ProcessorsType>
struct Parser<ReaderType, WriterType, Person, ProcessorsType>
    : public CustomParser<ReaderType, WriterType, ProcessorsType, Person, PersonImpl> {};

}  // namespace rfl::parsing
```

Now your custom class is fully supported by reflect-cpp. So for instance, you could parse it
inside a vector:

```cpp
const auto people = rfl::json::read<std::vector<Person>>(json_str).value();
```

As we have noted, in this particular example, the `Person` class can be constructed from the field values in
`PersonImpl` in the exact same order they were declared in `PersonImpl`. So we can drop the `.to_class` method:

```cpp
struct PersonImpl {
    rfl::Rename<"firstName", std::string> first_name;
    rfl::Rename<"lastName", std::string> last_name;
    int age;

    static PersonImpl from_class(const Person& _p) noexcept {
        return PersonImpl{.first_name = _p.first_name(),
                          .last_name = _p.last_name(),
                          .age = _p.age()};
    }
};
```

## Implement the `Parser` template

You can also directly implement the Parser template for your type.
This might be beneficial when you have a third-party container type
that behaves like standard containers.

In our example, we are implementing the template for `gtl::flat_hash_map`,
but the approach should also work for similar boost containers.

```cpp
namespace rfl {
namespace parsing {

template <class K, class V, class Hash, class KeyEqual, class Allocator>
class is_map_like<gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>> : public std::true_type {};

template <class R, class W, class T, class Hash, class KeyEqual, class ProcessorsType>
  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<std::string, T, Hash>>
struct Parser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType>
    : public MapParser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType> {};

template <class R, class W, typename K, typename V, class Hash, class KeyEqual, class Allocator, class ProcessorsType>
  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>>
struct Parser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType>
    : public VectorParser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType> {};

}
}
```