Added generic elements; resolves #96 (#125)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-06-27 23:05:48 +02:00
committed by GitHub
parent c3db8321b3
commit 28b89ae0df
23 changed files with 1012 additions and 39 deletions
+28 -20
View File
@@ -44,42 +44,50 @@
2.5) [JSON schema](https://github.com/getml/reflect-cpp/blob/main/docs/json_schema.md) - For validating your schema before you even send it to your C++ backend.
## 3) Custom classes
## 3) Generic elements
3.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
3.1) [rfl::Object](https://github.com/getml/reflect-cpp/blob/main/docs/object.md) - A map-like type representing a object with field names that are unknown at compile time.
3.2) [Custom parsers for your classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md) - For custom classes with private fields that you want to leave absolutely untouched.
3.2) [rfl::Generic](https://github.com/getml/reflect-cpp/blob/main/docs/generic.md) - A catch-all type that can represent (almost) anything.
## 4) Useful helper functions and classes
3.3) [rfl::ExtraFields](https://github.com/getml/reflect-cpp/blob/main/docs/extra_fields.md) - For adding extra fields to your structs, the names of which are unknown at compile time.
4.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct.
## 4) Custom classes
4.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs.
4.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
4.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing.
4.2) [Custom parsers for your classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md) - For custom classes with private fields that you want to leave absolutely untouched.
4.4) [rfl::to_view](https://github.com/getml/reflect-cpp/blob/main/docs/to_view.md) - For accessing fields of a struct by index or name.
## 5) Useful helper functions and classes
## 5) Supported formats
5.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct.
5.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md)
5.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs.
5.2) [BSON](https://github.com/getml/reflect-cpp/blob/main/docs/bson.md)
5.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing.
5.3) [CBOR](https://github.com/getml/reflect-cpp/blob/main/docs/cbor.md)
5.4) [rfl::to_view](https://github.com/getml/reflect-cpp/blob/main/docs/to_view.md) - For accessing fields of a struct by index or name.
5.4) [flexbuffers](https://github.com/getml/reflect-cpp/blob/main/docs/flexbuffers.md)
## 6) Supported formats
5.5) [msgpack](https://github.com/getml/reflect-cpp/blob/main/docs/msgpack.md)
6.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md)
5.6) [TOML](https://github.com/getml/reflect-cpp/blob/main/docs/toml.md)
6.2) [BSON](https://github.com/getml/reflect-cpp/blob/main/docs/bson.md)
5.7) [XML](https://github.com/getml/reflect-cpp/blob/main/docs/xml.md)
6.3) [CBOR](https://github.com/getml/reflect-cpp/blob/main/docs/cbor.md)
5.8) [YAML](https://github.com/getml/reflect-cpp/blob/main/docs/yaml.md)
6.4) [flexbuffers](https://github.com/getml/reflect-cpp/blob/main/docs/flexbuffers.md)
## 6) Advanced topics
6.5) [msgpack](https://github.com/getml/reflect-cpp/blob/main/docs/msgpack.md)
6.1) [Supporting your own format](https://github.com/getml/reflect-cpp/blob/main/docs/supporting_your_own_format.md) - For supporting your own serialization and deserialization formats.
6.6) [TOML](https://github.com/getml/reflect-cpp/blob/main/docs/toml.md)
6.2) [Maintaining backwards compatability](https://github.com/getml/reflect-cpp/blob/main/docs/backwards_compatability.md) - Instructions on how to ensure that your API is backwards-compatible with older versions.
6.7) [XML](https://github.com/getml/reflect-cpp/blob/main/docs/xml.md)
6.8) [YAML](https://github.com/getml/reflect-cpp/blob/main/docs/yaml.md)
## 7) Advanced topics
7.1) [Supporting your own format](https://github.com/getml/reflect-cpp/blob/main/docs/supporting_your_own_format.md) - For supporting your own serialization and deserialization formats.
7.2) [Maintaining backwards compatability](https://github.com/getml/reflect-cpp/blob/main/docs/backwards_compatability.md) - Instructions on how to ensure that your API is backwards-compatible with older versions.
+58
View File
@@ -0,0 +1,58 @@
# `rfl::ExtraFields`
In some cases, you simply do not know all of the possible field names at compile time. You might know some, but you
do not know all of them.
Note that there are many ways of dealing with these kind of uncertainties, such as optional fields or tagged unions.
But in instance where the field names are absolutely not known in advance, you might want to use `rfl::ExtraFields`:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
```
Note that `rfl::ExtraFields` inherits from `rfl::Object` and therefore behaves exactly like it. Refer
to the relevant section of the documentation on `rfl::Object`.
This will result in the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","age":45,"email":"homer@simpson.com","town":"Springfield"}
```
Likewise, when we parse the JSON string, all of the fields that can't be directly matched to
a known field will be parsed into `extra_fields`.
Note that in this particular instance, we have set the type to `rfl::Generic`. But if we know in
advance that all of the extra fields must be strings, we can set it to `std::string` as well:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
rfl::ExtraFields<std::string> extra_fields;
};
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
```
This will result in the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","email":"homer@simpson.com","town":"Springfield"}
```
If we add an extra field that is not a string (like `"age":45`), this will result in a parsing error.
+87
View File
@@ -0,0 +1,87 @@
# `rfl::Generic`
reflect-cpp is intended to be used to directly parse into structs. Doing this is more efficient, more convenient and also safer.
But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we
have `rfl::Generic`.
`rfl::Generic` is a convenience wrapper around the following type:
```cpp
std::variant<bool, int, double, std::string, Object, Array>;
```
`Object` and `Array` are defined as follows:
```cpp
using Array = std::vector<Generic>;
using Object = rfl::Object<Generic>;
```
In other words, `rfl::Generic` encompasses all types that can be expressed in JSON.
It can be used as follows:
```cpp
auto bart = rfl::Generic::Object();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["age"] = 10;
auto lisa = rfl::Generic::Object();
lisa["first_name"] = "Lisa";
lisa["last_name"] = "Simpson";
lisa["age"] = 8;
auto maggie = rfl::Generic::Object();
maggie["first_name"] = "Lisa";
maggie["last_name"] = "Simpson";
maggie["age"] = 0;
auto homer = rfl::Generic::Object();
homer["first_name"] = "Homer";
homer["last_name"] = "Simpson";
homer["age"] = 45;
homer["children"] = rfl::Generic::Array({bart, lisa, maggie});
```
The resulting JSON strings looks as follows:
```json
{"first_name":"Homer","last_name":"Simpson","age":45,"children":[{"first_name":"Bart","last_name":"Simpson","age":10},{"first_name":"Lisa","last_name":"Simpson","age":8},{"first_name":"Lisa","last_name":"Simpson","age":0}]}
```
`rfl::Generic` contains some convenience methods that allow you to handle parsed data:
You can retrieve the underlying `std::variant` using `.get()`. This then allows you to handle allow possible six cases using the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit).
If you have a guess what the types of a particular field might be, you can use any of the six convenience methods `.to_array()`, `.to_bool()`, `.to_double()`, `.to_int()`, `.to_object()`, `.to_string()`. Each
of these methods will return an `rfl::Result<...>` with the corresponding type, if the `rfl::Generic` does indeed contain such a type.
If you prefer, you can also use the following six convenience *functions*:
`rfl::to_array(...)`, `rfl::to_bool(...)`, `rfl::to_double(...)`, `rfl::to_int(...)`, `rfl::to_object(...)`, `rfl::to_string(...)`.
These functions are particularly useful for monadic error handling:
```cpp
auto homer = rfl::Generic::Object();
...
rfl::Result<int> age = homer.get("age").and_then(rfl::to_int);
```
In this particular instance, we know that `homer` is an `rfl::Generic::Object`. We assume that it has a field named `age` which we also assume is an integer.
In the end, we will get an `rfl::Result<int>` which will contain an integer, if both of our assumptions are correct and an error otherwise.
If we want to retrieve the age, we can use the `.value()` method:
```cpp
auto homer = rfl::Generic::Object();
...
int age = homer.get("age").and_then(rfl::to_int).value();
```
This will throw an exception if any of our assumptions are false.
Please refer to the part of the documentation on `rfl::Result` to learn more about monadic error handling.
+65
View File
@@ -0,0 +1,65 @@
# `rfl::Object`
`rfl::Object<...>` behaves similarly to `rfl::map<std::string, ...>` and `rfl::unordered_map<std::string, ...>`.
It will be represented in JSON or other formats as an object:
```cpp
auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";
```
This is results in the following JSON string:
```cpp
{"first_name":"Bart","last_name":"Simpson","town":"Springfield"}
```
It supports almost all of the normal features you would expect from such a container. For instance,
you can iterate through it just like any other map:
```cpp
for (const auto& [k, v]: bart) {
std::cout << k << ": " << v << std::endl;
}
```
However, unlike these containers, the order of fields is preserved. It is also possible to have duplicate keys:
```cpp
auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";
// Note that you need the .insert(...) method,
// because operator[] would overwrite the
// existing field.
bart.insert("first_name", "Lisa");
```
This results in the following JSON string:
```cpp
{"first_name":"Bart","last_name":"Simpson","town":"Springfield","first_name":"Lisa"}
```
There are three different ways of inserting fields:
- `operator[...]` creates a new field, if a field of this name doesn't already exist, and then assigns it.
- `.insert(...)` inserts a new field at the end, potentially creating duplicate field names. Much like `std::map`, it supports several types of inputs:
- `.insert(std::pair(key, value))`
- `.insert(key, value)`
- `.insert(begin, end)`, where `begin` and `end` are iterators of a container of key-value-pairs
- `.emplace(...)` is an alias for `.insert` that exists primarily for reasons of compatability with standard containers.
There are three different ways of accessing fields:
- `operator[...]` creates a new field, if a field of this name doesn't already exist.
- `.at(...)` throws an exception, if field of this name doesn't exist.
- `.get(...)` returns an `rfl::Result` wrapping the field, or an `rfl::Error` if the field doesn't exist.
Note that it is most efficient, if you access fields in the order that they were placed.