Merge branch 'main' into feature/validator

This commit is contained in:
Jeremy Perez
2023-10-27 13:07:49 +02:00
54 changed files with 2382 additions and 1630 deletions
+32 -6
View File
@@ -3,8 +3,8 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity)
[![Generic badge](https://img.shields.io/badge/C++-20-blue.svg)](https://shields.io/)
[![Generic badge](https://img.shields.io/badge/gcc-10+-blue.svg)](https://shields.io/)
[![Generic badge](https://img.shields.io/badge/clang-TODO-red.svg)](https://shields.io/)
[![Generic badge](https://img.shields.io/badge/gcc-11+-blue.svg)](https://shields.io/)
[![Generic badge](https://img.shields.io/badge/clang-14+-blue.svg)](https://shields.io/)
[![Generic badge](https://img.shields.io/badge/MSVC-TODO-red.svg)](https://shields.io/)
![image](banner1.png)
@@ -19,7 +19,7 @@ Design principles for reflect-cpp include:
- Close integration with containers from the C++ standard library
- Close adherence to C++ idioms
- Out-of-the-box support for JSON, no dependencies
- Out-of-the-box support for JSON
- Simple installation: If no JSON support is required, reflect-cpp is header-only. For JSON support, only a single source file needs to be compiled.
- Simple extendability to other serialization formats
- Simple extendability to custom classes
@@ -92,6 +92,23 @@ std::cout << "Hello, my name is " << homer2.first_name() << " "
<< homer2.last_name() << "." << std::endl;
```
reflect-cpp returns clear and comprehensive error messages:
```cpp
const std::string faulty_json_string =
R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})";
const auto result = rfl::json::read<Person>(faulty_json_string);
```
Yields the following error message:
```
Found 3 errors:
1) Failed to parse field 'lastName': Could not cast to string.
2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'.
3) Field named 'children' not found.
```
## Support for containers
### C++ standard library
@@ -101,7 +118,9 @@ reflect-cpp supports the following containers from the C++ standard library:
- `std::array`
- `std::deque`
- `std::forward_list`
- `std::map`
- `std::map`
- `std::multimap`
- `std::multiset`
- `std::list`
- `std::optional`
- `std::pair`
@@ -110,7 +129,9 @@ reflect-cpp supports the following containers from the C++ standard library:
- `std::string`
- `std::tuple`
- `std::unique_ptr`
- `std::unordered_map`
- `std::unordered_map`
- `std::unordered_multimap`
- `std::unordered_multiset`
- `std::unordered_set`
- `std::variant`
- `std::vector`
@@ -149,10 +170,15 @@ At the moment, this is work-in-progress. Here are some things that are still mis
- Benchmarks and optimization
- Documentation is unfinished (missing rfl::Result, rfl::NamedTuple as well as extension to other serialization formats)
- Support for Clang and MSVC
- Support for MSVC
## Installation
The following compilers are supported:
- GCC 11.4 or higher
- Clang 14.0 or higher
- MSVC (TODO)
### Option 1: Header-only
If you **do not** need JSON support, then reflect-cpp is header-only. Simply copy the contents of the folder `include` into your source repository or add it to your include path.
+15
View File
@@ -18,6 +18,8 @@
1.7) [rfl::Timestamp](https://github.com/getml/reflect-cpp/blob/main/docs/timestamps.md) - For serializing and deserializing timestamps.
1.8) [Standard containers](https://github.com/getml/reflect-cpp/blob/main/docs/standard_containers.md) - Describes how reflect-cpp treats containers in the standard library.
## 2) Custom classes
2.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
@@ -29,3 +31,16 @@
3.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct.
3.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs.
3.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing
3.4) [rfl::Result](https://github.com/getml/reflect-cpp/blob/main/docs/result.md) - For error handling without exceptions
## 4) Supported formats
4.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md)
## 5) Advanced topics
5.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.
+1 -1
View File
@@ -96,7 +96,7 @@ 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 declaced in `PersonImpl`. So we can drop the `.to_class` method:
`PersonImpl` in the exact same order they were declared in `PersonImpl`. So we can drop the `.to_class` method:
```cpp
struct PersonImpl {
+81
View File
@@ -0,0 +1,81 @@
# JSON
For JSON support, you must also include the header `<rfl/json.hpp>`.
## Reading and writing
Suppose you have a struct like this:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Field<"children", std::vector<Person>> children;
};
```
You can parse JSON strings like this:
```cpp
const rfl::Result<Person> result = rfl::json::read<Person>(json_string);
```
A person can be turned into a JSON string like this:
```cpp
const auto person = Person{...};
const std::string json_string = rfl::json::write(person);
```
## Loading and saving
You can also load and save to disc using a very similar syntax:
```cpp
const rfl::Result<Person> result = rfl::json::load<Person>("/path/to/file.json");
const auto person = Person{...};
rfl::json::save("/path/to/file.json", person);
```
## Custom constructors
One of the great things about C++ is that it gives you control over
when and how you code is compiled.
For large and complex systems of structs, it is often a good idea to split up
your code into smaller compilation units. You can do so using custom constructors.
For the JSON format, these must be a static function on your struct or class called
`from_json_obj` that take a `rfl::json::Reader::InputVarType` as input and return
the class or the class wrapped in `rfl::Result`.
In your header file you can write something like this:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
using JSONVar = typename rfl::json::Reader::InputVarType;
static rfl::Result<Person> from_json_obj(const JSONVar& _obj);
};
```
And in your source file, you implement `from_json_obj` as follows:
```cpp
rfl::Result<Person> Person::from_json_obj(const JSONVar& _obj) {
const auto from_nt = [](auto&& _nt) {
return rfl::from_named_tuple<Person>(std::move(_nt));
};
return rfl::json::read<rfl::named_tuple_t<Person>>(_obj)
.transform(from_nt);
}
```
This will force the compiler to only compile the JSON parsing when the
source file is compiled.
+250
View File
@@ -0,0 +1,250 @@
# `rfl::NamedTuple`
`rfl::NamedTuple` is very similar to `std::tuple`, but unlike `std::tuple` the fields have names.
In other words, consider the following struct:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
};
```
You might as well define the following `rfl::NamedTuple`:
```cpp
using Person = rfl::NamedTuple<
rfl::Field<"firstName", std::string>,
rfl::Field<"lastName", std::string>,
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>;
```
From the point-of-view of serialization/deserialization, the two definitions are equivalent.
The resulting JSON strings (or any other format) will be the same.
## Structural typing
From the point-of-view of programming, there is an important difference: Structs are *nominally typed*
and named tuples are *structurally typed* (confusingly, structs are not structurally typed).
In plain language, that means that the compiler will regard this as absolutely equivalent to `Person`, the named tuple:
```cpp
using Person2 = rfl::NamedTuple<
rfl::Field<"firstName", std::string>,
rfl::Field<"lastName", std::string>,
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>;
```
However, this will be seen as a type that is different from `Person`, the struct:
```cpp
struct Person2 {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
};
```
Structural typing also means that you can declare new types on-the-fly. For instance, in order
to create a `Person` named tuple, you don't actually have to declare it at all. The following will do:
```cpp
const auto person = rfl::Field<"firstName", std::string>("Homer") *
rfl::Field<"lastName", std::string>("Simpson") *
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19");
```
The type of `person` will now be equivalent to the definition of `Person`, the named tuple,
regardless of whether you have actually declared it anywhere.
On the other hand, structural typing also means that recursive definitions are impossible.
For instance, consider something like this:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"children", std::vector<Person>> children;
};
```
In this example, `Person` is recursively defined (because of the field `children`).
This is impossible to accomplish using structural typing and `rfl::NamedTuple`, just like it is impossible to have a recursively defined lambda function.
## Accessing fields
Fields inside the named tuple can be accessed using `rfl::get` or the `.get` method:
```cpp
const auto person = rfl::Field<"firstName", std::string>("Homer") *
rfl::Field<"lastName", std::string>("Simpson") *
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19");
// OK in most circumstances (there are restrictions
// due to the way C++ templates work).
const auto first_name = person.get<"firstName">();
// Always OK
const auto first_name = person.template get<"firstName">();
// Always OK
const auto first_name = rfl::get<"firstName">(person);
```
## Similarity to structs
Most of the functionality we have described also work for `rfl::NamedTuple`.
It should be noted that you are free to mix `rfl::NamedTuple` and structs.
For instance, you can build a `rfl::TaggedUnion` from a combination of
`rfl::NamedTuple` and structs or you could construct a struct from named tuples using
`rfl::as`.
### `std::variant` and `rfl::TaggedUnion`
`rfl::NamedTuple`s can be inserted into `std::variant`:
```cpp
using Circle = rfl::NamedTuple<rfl::Field<"radius", double>>;
using Rectangle = rfl::NamedTuple<
rfl::Field<"height", double>,
rfl::Field<"width", double>>;
using Square rfl::NamedTuple<rfl::Field<"width", double>>;
// Untagged variant - OK
using Shapes = std::variant<Circle, Rectangle, Square>;
// Externally tagged variant - also OK:
using Shapes = std::variant<rfl::Field<"circle", Circle>,
rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", Square>>;
```
They can also be inserted into `rfl::TaggedUnion`:
```cpp
using Circle = rfl::NamedTuple<
rfl::Field<"shape", rfl::Literal<"Circle">>,
rfl::Field<"radius", double>>;
using Rectangle = rfl::NamedTuple<
rfl::Field<"shape", rfl::Literal<"Rectangle">>,
rfl::Field<"height", double>,
rfl::Field<"width", double>>;
using Square rfl::NamedTuple<
rfl::Field<"shape", rfl::Literal<"Square">>,
rfl::Field<"width", double>>;
// Tell rfl::TaggedUnion that you want it to look for the field "shape".
using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>;
```
### `rfl::replace`
`rfl::replace` works for `rfl::NamedTuple` as well:
```cpp
const auto lisa = rfl::Field<"firstName", std::string>("Lisa") *
rfl::Field<"lastName", std::string>("Simpson");
// Returns a deep copy of the original object,
// replacing first_name.
const auto maggie =
rfl::replace(lisa, rfl::make_field<"firstName">(std::string("Maggie")));
// Also OK
const auto bart = lisa.replace(rfl::make_field<"firstName">(std::string("Bart")));
```
### `rfl::as`
So does `rfl::as`:
```cpp
using C = rfl::NamedTuple<
rfl::Field<"f1", std::string>,
rfl::Field<"f2", std::string>,
rfl::Field<"f4", std::string>>;
const auto a = rfl::Field<"f1", std::string>("Hello") *
rfl::Field<"f2", std::string>("World");
const auto b = rfl::Field<"f3", std::string>("Hello") *
rfl::Field<"f4", std::string>("World");
const auto c = rfl::as<C>(a, b);
```
However, you do not really have to use `rfl::as` here. This will work as well:
```cpp
// Same as rfl::as<C>(a, b)
const auto c = C(a * b);
```
(in fact, this is how `rfl::as` is implemented in the first place).
## Defining named tuples using other named tuples
`rfl::Flatten` is not supported inside named tuples. Instead, you can use `rfl::define_named_tuple_t<...>`
to achieve the same goal:
```cpp
using Person = rfl::NamedTuple<
rfl::Field<"firstName", std::string>,
rfl::Field<"lastName", std::string>,
rfl::Field<"age", int>>;
using Employee = rfl::define_named_tuple_t<
Person,
rfl::Field<"salary", float>>;
const auto employee = Employee(
rfl::Field<"firstName", std::string>("Homer"),
rfl::Field<"lastName", std::string>("Simpson"),
rfl::make_field<"age">(45),
rfl::make_field<"salary">(60000.0));
```
## Transforming structs to named tuples and vice versa
You can transform structs to named tuples and vice versa:
```cpp
auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19"};
// bart_nt is a named tuple
const auto bart_nt = rfl::to_named_tuple(bart);
// You can also retrieve the equivalent named tuple
// type to a struct:
using PersonNamedTuple = rfl::named_tuple_t<Person>;
// rfl::to_named_tuple also supports move semantics
PersonNamedTuple bart_nt = rfl::to_named_tuple(std::move(bart_nt));
// You can also go the other way
const auto bart_struct = rfl::from_named_tuple<Person>(bart_nt);
const auto bart_struct = rfl::from_named_tuple<Person>(std::move(bart_nt));
```
## rfl::NamedTuple is central to reflect-cpp
`rfl::NamedTuple` is basically at the heart of how the reflect-cpp reflection
is actually implemented. If you look at how reflect-cpp is implemented you will find that
structs are transformed from and to `rfl::NamedTuple`s
all the time (using zero-copy operations wherever possible).
That is because `rfl::NamedTuple` actually support reflection,
where as structs don't.
+138
View File
@@ -0,0 +1,138 @@
# `rfl::Result`
In this documentation, we have, on several occasions, read a JSON string like this:
```cpp
const auto homer = rfl::json::read<Person>(json_string).value();
```
However, so far we have not elaborated on why `.value()` is necessary. Why can't we just do this?
```cpp
const auto homer = rfl::json::read<Person>(json_string);
```
The reason is that parsing a JSON string is something that might fail. We do not know much about
the string that put into there. It might not be a valid JSON. And even if it is a valid JSON, then it
might not conform to the assumptions that we have made about it and laid out in the type system
in the form of various structs and containers.
`rfl::json::read` handles this by returning an `rfl::Result` type. `rfl::Result` is a way of error
handling without exceptions. Exceptions are controversial, because they add another, hidden control
path to your program that it hard to follow or predict. For this reasons, and others, the Google
C++ style guide [disallows exceptions altogether](https://google.github.io/styleguide/cppguide.html#Exceptions).
Modern programming languages like Go and Rust don't even support them in the first place. The C++
standards committee has recognized this and introduced [std::expected](https://en.cppreference.com/w/cpp/utility/expected)
in C++-23.
However, reflect-cpp is a library for C++-20 and until that changes, we need to implement our own result type.
If you do not care about these objections to exceptions, you can just call `rfl::json::read<...>(json_string).value()`,
which throws an exception, if the result type contains an error and be done with it.
## What is `rfl::Result`?
`rfl::Result` is similar to `std::optional` it that it contains an object that may or may not be there. However,
unlike `std::optional`, it does not simply contain `std::nullopt` if the operation has not been successful. Instead,
it contains an `rfl::Error` with a clear error message.
In laying out our structs an containers, about the the type system, we are making *requirements* about the
JSON input we are expecting from the outside world. `rfl::json::read<T>(...)` checks whether these requirements are met.
If the requirements are met, `rfl::json::read<T>` returns T wrapped inside `rfl::Result`. If they are not met, it returns
`rfl::Error` containing an error message explaining what went wrong.
## Monadic operations
From the point of view of category theory, `rfl::Result` is both a functor and a monad (actually, all monads are functors).
This is reflected in its member functions `.transform(...)` and `.and_then(...)`.
`.transform(...)` requires a function `F` of the type `T -> U`. If the `rfl::Result<T>` contains a type `T`,
then `r.transform(f)` *will* return an `rfl::Result<U>` containing a type `U`, otherwise it will return an `rfl::Result<U>`
containing an error.
`.and_then(...)` requires a function `F` of the type `T -> rfl::Result<U>`. If the `rfl::Result<T>` contains a type `T`,
then `r.and_then(f)` *might* return an `rfl::Result<U>` containing a type `U`, depending on whether `f` failed.
If `r` already contained an error, then `r.and_then(f)` will surely return an `rfl::Result<U>` containing an error.
containing an error.
Throughout reflect-cpp's code, these functions are widely used by the parser. For instance, consider how we are reading
`std::unique_ptr<T>` (note that this is somewhat simplified):
```cpp
const auto to_ptr = [](auto&& _t) {
return std::make_unique<T>(std::move(_t));
};
return Parser<T>::read(_r, _var).transform(to_ptr);
```
This code works as follows: First, we read in a type `T`, which is something that might fail. However, we know 100% that
once we have `T` we can surely wrap it inside a pointer, so we can call `.transform(...)`.
On the other hand, consider the implementation of `rfl::json::load`, which loads a JSON from a file:
```cpp
template <class T>
Result<T> load(const std::string& _fname) {
return rfl::io::load_string(_fname).and_then(read<T>);
}
```
This code works as follows: First, we read in the text file using `rfl::io::load_string`. This an operation that might fail (maybe
the file doesn't exist, maybe it isn't readable, ...). Then we have to to parse its contents using `rfl::json::read<T>`. Again,
this is an operation that might fail (might not be a proper JSON, might not conform to our requirements, ...). Therefore, we
have to call `.and_then(...)`.
## Retrieving values or errors
If you want the underlying value of type T, you can use `.value(...)`. Note that this throws an exception, if `rfl::Result<T>` contains
an error.
If you are 100% sure that the result does not contain error, you can also call the operator `*`. This will lead to undefined behavior,
if you are wrong.
If you want the underlying value of type T or some kind of default value, you can call `.value_or(your_default_value)`.
If you want to retrieve the error, you can call `.error()`, which will return a value of type `std::optional<rfl::Error>`.
If you want to check whether the result contains an error, you can just use the bool operator:
```cpp
if (my_result) {
// my_result cannot contain an error,
// so it is okay to call operator *.
auto v = *my_result;
} else {
// my_result must contain an error.
auto err = my_result.error().value();
}
```
## Iterating over `rfl::Result`
`rfl::Result` can be iterated over, as it contains either zero or one values of type `T`:
```cpp
for (const auto& v: my_result) {
// If you are inside this loop, then my_result did not contain an error.
}
```
## `.and_other(...)`, `.or_else(...)`, `.or_other(...)`
`r1.and_other(r2)` expects an `r2` or type `rfl::Result<U>`. It returns an error, if `r1` contains an error and `r2` otherwise.
`r.or_else(f)` expects a function `f` for type `Error -> rfl::Result<T>`. It returns `r` if `r` did not contain an error and the results of `f` otherwise.
This is often used to produce better error messages:
```cpp
const auto embellish_error = [&](const Error& _e) -> rfl::Result<T> {
return Error("Failed to parse field '" + key + "': " + _e.what());
};
return Parser<T>::read(_r, &_var).or_else(embellish_error);
```
`r1.or_other(r2)` expects an `r2` or type `rfl::Result<T>`. It returns an `r1`, if `r1` does not contain an error and `r2` otherwise.
+41
View File
@@ -0,0 +1,41 @@
# Support for standard containers
The serialization and deserialization of containers is handled as follows:
`std::map<std::string, ...>` and `std::unordered_map<std::string, ...>` are treated
as objects.
Consider the following map:
```cpp
std::map<std::string, std::string> homer;
homer["firstName"] = "Homer";
homer["lastName"] = "Simpson";
```
This will be represented as follows:
```json
{"firstName":"Homer","lastName":"Simpson"}
```
All other supported standard containers
(other than `std::variant`, `std::optional`, `std::unique_ptr` and `std::shared_ptr`)
will be represented as arrays. Containers for which the `value_type`
is a key-value-pair, will be represented as arrays of pairs.
Consider the following map:
```cpp
std::map<int, Person> children;
children[1] = Person{.first_name = "Bart", .last_name = "Simpson"};
children[2] = Person{.first_name = "Lisa", .last_name = "Simpson"};
children[3] = Person{.first_name = "Maggie", .last_name = "Simpson"};
```
This will be represented as follows:
```json
[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]]
```
+219
View File
@@ -0,0 +1,219 @@
# Supporting your own format
In order to support your own serialization format, you need to implement a reader and a writer on top of whatever serialization libary
you have chosen.
The reader and writer constitute a thin layer between the serialization library of your choice and reflect-cpp.
The requirements are laid down in the concepts [IsReader](https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsReader.hpp) and
[IsWriter](https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsWriter.hpp) and also documented below.
Using the reader and the writer you can define your parser like this:
```cpp
template <class T>
using YourParser = rfl::parsing::Parser<YourReader, YourWriter, T>;
```
This can then be used to implement a `read` function and a `write` function:
```cpp
using InputVarType = typename YourReader::InputVarType;
using OutputVarType = typename YourWriter::OutputVarType;
template <class T>
rfl::Result<T> read(const std::string& _str) {
// This should be supported by whatever library you are
// using for your format.
const InputVarType root = str_to_input_var(_str);
// You can pass variables to the constructor, if necessary
const auto r = Reader(...);
return YourParser<T>::read(r, root);
}
template <class T>
std::string write(const T& _obj) {
// You can pass variables to the constructor, if necessary
auto w = Writer(...);
OutputVarType var = Parser<T>::write(w, _obj);
// This should be supported by whatever library you are
// using for your format.
return output_var_to_str(var);
}
```
In the following two sections, we will provide templates for your `Reader` and `Writer`.
You should probably just copy + paste this into your own code and fill in the blanks.
As a reference, you can take a look at how this is done for JSON: https://github.com/getml/reflect-cpp/tree/main/include/rfl/json
## Implementing your own writer
Because writers are somewhat simpler, we will start with them.
Any Writer needs to define the following types:
1) An `OutputArrayType`, which must be an array-like data structure.
2) An `OutputObjectType`, which must contain key-value pairs.
3) An `OutputVarType`, which must be able to represent either
`OutputArrayType`, `OutputObjectType` or a basic type (bool, integral,
floating point, std::string). We hesitate to call these "primitive types",
because primitive types in C++ are defined as a slightly different group
of types.
It also needs to support the following methods:
```cpp
struct Writer {
using OutputArrayType = ...;
using OutputObjectType = ...;
using OutputVarType = ...;
/// Appends `_var` to the end of `_arr`, thus mutating it.
void add(const OutputVarType _var, OutputArrayType* _arr) const noexcept {...}
/// Returns an empty OutputVarType, the NULL type of the format.
OutputVarType empty_var() const noexcept {...}
/// Generates an OutputVarType from a basic type
/// (std::string, bool, floating point or integral).
template <class T>
OutputVarType from_basic_type(const T& _var) const noexcept {...}
/// Generates a new, empty array.
OutputArrayType new_array() const noexcept {...}
/// Generates a new, empty object.
OutputObjectType new_object() const noexcept {...}
/// Determines whether the var is empty (whether it is the NULL type).
bool is_empty(const OutputVarType& _var) const noexcept {...}
/// Adds a new field to obj, thus mutating it.
void set_field(const std::string& _name, const OutputVarType& _var,
OutputObjectType* _obj) const noexcept {...}
};
```
## Implementing your own reader
Any Reader needs to define the following:
1) An `InputArrayType`, which must be an array-like data structure.
2) An `InputObjectType`, which must contain key-value pairs.
3) An `InputVarType`, which must be able to represent either
`InputArrayType`, `InputObjectType` or a basic type (bool, integral,
floating point, std::string).
4) A `static constexpr bool has_custom_constructor<T>`, that determines
whether the class in question as a custom constructor, which might
be called something like `from_json_obj(...)`. If you do not want to
support this functionality, just set it to false.
It also needs to support the following methods:
```cpp
struct Reader {
using InputArrayType = ...;
using InputObjectType = ...;
using InputVarType = ...;
/// If you do not want to support custom constructors,
/// just set this to false.
template <class T>
static constexpr bool has_custom_constructor = false;
/// Retrieves a particular field from an object.
/// Returns an rfl::Error if the field cannot be found.
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType& _obj) const noexcept {...}
/// Determines whether a variable is empty (the NULL type).
bool is_empty(const InputVarType& _var) const noexcept {...}
/// Cast _var as a basic type (bool, integral,
/// floating point, std::string).
/// Returns an rfl::Error if it cannot be cast
/// as that type
template <class T>
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {...}
/// Casts _var as an InputArrayType.
/// Returns an rfl::Error if `_var` cannot be cast as an array.
rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept {...}
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
/// See below for a more comprehensive explanation.
template <size_t size, class FunctionType>
std::array<InputVarType, size> to_fields_array(
const FunctionType _fct, const InputObjectType& _obj) const noexcept {...}
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType& _obj) const noexcept {...}
/// Casts _var as an InputObjectType.
/// Returns an rfl::Error if `_var` cannot be cast as an object.
rfl::Result<InputObjectType> to_object(
const InputVarType& _var) const noexcept {...}
/// Iterates through an array and writes the contained values into
/// a std::vector<InputVarType>.
std::vector<InputVarType> to_vec(const InputArrayType& _arr) const noexcept {...}
/// Constructs T using its custom constructor. This will only be triggered if
/// T was determined to have a custom constructor by
/// static constexpr bool has_custom_constructor, as defined above.
/// Returns an rfl::Error, if the custom constructor throws an exception.
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType& _var) const noexcept {
// If you do not want to support this functionality,
// just return this.
return rfl::Error("Not supported.");
}
};
```
Of these methods, `to_fields_array` probably requires futher explanation.
Consider the following struct:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Field<"children", std::vector<Person>> children;
};
```
This struct contains four fields. `rfl::parsing::Parser` expects `to_fields_array`
to return an `std::array<InputVarType, 4>` containing the field "firstName" in the
first position, "lastName" in the second position, "birthday" in the third position
and "children" in the fourth position.
`rfl::parsing::Parser` will pass the following two elements:
1. A function `_fct` of type `FunctionType`.
2. An object `_obj` of type `InputObjectType`.
`_fct` takes a field name of type `std::string_view` as an input and
returns an index. This index signifies the position in the `std::array`
it wants this field to have. If the field is not contained in the struct,
the index will be -1.
Your job is to implement the following:
1. Iterate through `_obj`.
2. Identify the required index of the field name using `_fct`.
3. Set the corresponding field in `std::array` to the field value associated with the field name.
4. Any field that could not be set in steps 1-3 must be set to the NULL value,
such that `Reader.is_empty(...)` would return `true`.
+38 -10
View File
@@ -18,34 +18,50 @@ class Box {
return Box<T>(std::make_unique<T>(std::forward<Args>(_args)...));
}
Box() : ptr_(std::make_unique<T>()) {}
Box(const Box<T>& _other) = delete;
Box(Box<T>&& _other) : ptr_(std::move(_other.ptr_)) {}
Box(Box<T>&& _other) = default;
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Box(Box<U>&& _other) noexcept
: ptr_(std::make_unique<T>(std::forward<U>(*_other))) {}
~Box() = default;
/// Returns a pointer to the underlying object
inline T* get() const { return ptr_.get(); }
T* get() const { return ptr_.get(); }
/// Copy assignment operator
inline Box<T>& operator=(const Box<T>& _other) = delete;
Box<T>& operator=(const Box<T>& _other) = delete;
/// Move assignment operator
inline Box<T>& operator=(Box<T>&& _other) noexcept {
if (&_other != this) {
ptr_ = std::move(_other.ptr_);
}
Box<T>& operator=(Box<T>&& _other) noexcept = default;
/// Move assignment operator
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Box<T>& operator=(Box<U>&& _other) noexcept {
ptr_ = std::make_unique<T>(std::forward<U>(*_other));
return *this;
}
/// Returns the underlying object.
inline T& operator*() const { return *ptr_; }
T& operator*() { return *ptr_; }
/// Returns the underlying object.
inline T* operator->() const { return ptr_.get(); }
T& operator*() const { return *ptr_; }
/// Returns the underlying object.
T* operator->() { return ptr_.get(); }
/// Returns the underlying object.
T* operator->() const { return ptr_.get(); }
/// Returns the underlying unique_ptr
inline const std::unique_ptr<T>& ptr() const { return ptr_; }
const std::unique_ptr<T>& ptr() const { return ptr_; }
private:
/// Only make is allowed to use this constructor.
@@ -62,6 +78,18 @@ Box<T> make_box(Args&&... _args) {
return Box<T>::make(std::forward<Args>(_args)...);
}
template <class T1, class T2>
inline auto operator<=>(const Box<T1>& _t1, const Box<T2>& _t2) {
return _t1.ptr() <=> _t2.ptr();
}
template <class CharT, class Traits, class T>
inline std::basic_ostream<CharT, Traits>& operator<<(
std::basic_ostream<CharT, Traits>& _os, const Box<T>& _b) {
_os << _b.get();
return _os;
}
} // namespace rfl
#endif
+17 -28
View File
@@ -26,10 +26,9 @@ struct Field {
Field(Type&& _value) noexcept : value_(std::move(_value)) {}
Field(Field<_name, _Type>&& _field) noexcept
: value_(std::move(_field.value_)) {}
Field(Field<_name, _Type>&& _field) noexcept = default;
Field(const Field<_name, Type>& _field) : value_(_field.get()) {}
Field(const Field<_name, Type>& _field) = default;
template <class T>
Field(const Field<_name, T>& _field) : value_(_field.get()) {}
@@ -61,22 +60,22 @@ struct Field {
constexpr static const internal::StringLiteral name_ = _name;
/// Returns the underlying object.
inline const Type& get() const { return value_; }
const Type& get() const { return value_; }
/// Returns the underlying object.
inline Type& operator()() { return value_; }
Type& operator()() { return value_; }
/// Returns the underlying object.
inline const Type& operator()() const { return value_; }
const Type& operator()() const { return value_; }
/// Assigns the underlying object.
inline auto& operator=(const Type& _value) {
auto& operator=(const Type& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
inline auto& operator=(Type&& _value) noexcept {
auto& operator=(Type&& _value) noexcept {
value_ = std::move(_value);
return *this;
}
@@ -84,7 +83,7 @@ struct Field {
/// Assigns the underlying object.
template <class T, typename std::enable_if<std::is_convertible_v<T, Type>,
bool>::type = true>
inline auto& operator=(const T& _value) {
auto& operator=(const T& _value) {
value_ = _value;
return *this;
}
@@ -93,51 +92,41 @@ struct Field {
template <class T = Type,
typename std::enable_if<std::is_default_constructible_v<T>,
bool>::type = true>
inline auto& operator=(const Default& _default) {
auto& operator=(const Default& _default) {
value_ = Type();
return *this;
}
/// Assigns the underlying object.
inline Field<_name, _Type>& operator=(const Field<_name, _Type>& _field) {
if (&_field != this) {
value_ = _field.get();
}
return *this;
}
Field<_name, _Type>& operator=(const Field<_name, _Type>& _field) = default;
/// Assigns the underlying object.
inline Field<_name, _Type>& operator=(Field<_name, _Type>&& _field) {
if (&_field != this) {
value_ = std::move(_field.value_);
}
return *this;
}
Field<_name, _Type>& operator=(Field<_name, _Type>&& _field) = default;
/// Assigns the underlying object.
template <class T>
inline auto& operator=(const Field<_name, T>& _field) {
auto& operator=(const Field<_name, T>& _field) {
value_ = _field.get();
return *this;
}
/// Assigns the underlying object.
template <class T>
inline auto& operator=(Field<_name, T>&& _field) {
auto& operator=(Field<_name, T>&& _field) {
value_ = std::forward<T>(_field.value_);
return *this;
}
/// Assigns the underlying object.
inline void set(const Type& _value) { value_ = _value; }
void set(const Type& _value) { value_ = _value; }
/// Assigns the underlying object.
inline void set(Type&& _value) { value_ = std::move(_value); }
void set(Type&& _value) { value_ = std::move(_value); }
/// Returns the underlying object.
inline Type& value() { return value_; }
Type& value() { return value_; }
/// Returns the underlying object.
inline const Type& value() const { return value_; }
const Type& value() const { return value_; }
/// The underlying value.
Type value_;
+14 -26
View File
@@ -19,10 +19,9 @@ struct Flatten {
Flatten(Type&& _value) noexcept : value_(std::forward<Type>(_value)) {}
Flatten(const Flatten<_Type>& _f) : value_(_f.get()) {}
Flatten(const Flatten<_Type>& _f) = default;
Flatten(Flatten<_Type>&& _f) noexcept
: value_(std::forward<Type>(_f.value_)) {}
Flatten(Flatten<_Type>&& _f) noexcept = default;
template <class T>
Flatten(const Flatten<T>& _f) : value_(_f.get()) {}
@@ -41,22 +40,22 @@ struct Flatten {
~Flatten() = default;
/// Returns the underlying object.
inline const Type& get() const { return value_; }
const Type& get() const { return value_; }
/// Returns the underlying object.
inline Type& operator()() { return value_; }
Type& operator()() { return value_; }
/// Returns the underlying object.
inline const Type& operator()() const { return value_; }
const Type& operator()() const { return value_; }
/// Assigns the underlying object.
inline Flatten<_Type>& operator=(const _Type& _value) {
Flatten<_Type>& operator=(const _Type& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
inline Flatten<_Type>& operator=(_Type&& _value) {
Flatten<_Type>& operator=(_Type&& _value) {
value_ = std::forward<Type>(_value);
return *this;
}
@@ -64,46 +63,35 @@ struct Flatten {
/// Assigns the underlying object.
template <class T, typename std::enable_if<std::is_convertible_v<T, Type>,
bool>::type = true>
inline Flatten<_Type>& operator=(const T& _value) {
Flatten<_Type>& operator=(const T& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
inline Flatten<_Type>& operator=(const Flatten<_Type>& _f) {
if (&_f != this) {
value_ = _f.get();
}
return *this;
}
Flatten<_Type>& operator=(const Flatten<_Type>& _f) = default;
/// Assigns the underlying object.
inline Flatten<_Type>& operator=(Flatten<_Type>&& _f) {
if (&_f != this) {
value_ = std::move(_f.value_);
}
return *this;
}
Flatten<_Type>& operator=(Flatten<_Type>&& _f) = default;
/// Assigns the underlying object.
template <class T>
inline Flatten<_Type>& operator=(const Flatten<T>& _f) {
Flatten<_Type>& operator=(const Flatten<T>& _f) {
value_ = _f.get();
return *this;
}
/// Assigns the underlying object.
template <class T>
inline Flatten<_Type>& operator=(Flatten<T>&& _f) {
Flatten<_Type>& operator=(Flatten<T>&& _f) {
value_ = std::forward<T>(_f);
return *this;
}
/// Assigns the underlying object.
inline void set(const Type& _value) { value_ = _value; }
void set(const Type& _value) { value_ = _value; }
/// Assigns the underlying object.
inline void set(Type&& _value) { value_ = std::forward<Type>(_value); }
void set(Type&& _value) { value_ = std::forward<Type>(_value); }
/// The underlying value.
Type value_;
+23 -40
View File
@@ -34,10 +34,10 @@ class Literal {
static constexpr ValueType num_fields_ = sizeof...(fields_);
/// Constructs a Literal from another literal.
Literal(const Literal<fields_...>& _other) : value_(_other.value_) {}
Literal(const Literal<fields_...>& _other) = default;
/// Constructs a Literal from another literal.
Literal(Literal<fields_...>&& _other) noexcept : value_(_other.value_) {}
Literal(Literal<fields_...>&& _other) noexcept = default;
/// A single-field literal is special because it
/// can also have a default constructor.
@@ -48,20 +48,18 @@ class Literal {
~Literal() = default;
/// Determines whether the literal contains the string.
inline static bool contains(const std::string& _str) {
return has_value(_str);
}
static bool contains(const std::string& _str) { return has_value(_str); }
/// Determines whether the literal contains the string at compile time.
template <internal::StringLiteral _name>
inline static constexpr bool contains() {
static constexpr bool contains() {
return find_value_of<_name>() != -1;
}
/// Determines whether the literal contains any of the strings in the other
/// literal at compile time.
template <class OtherLiteralType, int _i = 0>
inline static constexpr bool contains_any() {
static constexpr bool contains_any() {
if constexpr (_i == num_fields_) {
return false;
} else {
@@ -74,7 +72,7 @@ class Literal {
/// Determines whether the literal contains all of the strings in the other
/// literal at compile time.
template <class OtherLiteralType, int _i = 0, int _n_found = 0>
inline static constexpr bool contains_all() {
static constexpr bool contains_all() {
if constexpr (_i == num_fields_) {
return _n_found == OtherLiteralType::num_fields_;
} else {
@@ -89,9 +87,7 @@ class Literal {
/// Determines whether the literal has duplicate strings at compile time.
/// These is useful for checking collections of strings in other contexts.
inline static constexpr bool has_duplicates() {
return has_duplicate_strings();
}
static constexpr bool has_duplicates() { return has_duplicate_strings(); }
/// Constructs a Literal from a string. Returns an error if the string
/// cannot be found.
@@ -113,26 +109,17 @@ class Literal {
/// Helper function to retrieve a name at compile time.
template <int _value>
inline constexpr static auto name_of() {
constexpr static auto name_of() {
constexpr auto name = find_name_within_own_fields<_value>();
return Literal<name>();
}
/// Assigns from another literal.
Literal<fields_...>& operator=(const Literal<fields_...>& _other) {
if (this != &_other) {
value_ = _other.value_;
}
return *this;
}
Literal<fields_...>& operator=(const Literal<fields_...>& _other) = default;
/// Assigns from another literal.
Literal<fields_...>& operator=(Literal<fields_...>&& _other) noexcept {
if (this != &_other) {
value_ = _other.value_;
}
return *this;
}
Literal<fields_...>& operator=(Literal<fields_...>&& _other) noexcept =
default;
/// Assigns the literal from a string
Literal<fields_...>& operator=(const std::string& _str) {
@@ -141,37 +128,33 @@ class Literal {
}
/// Equality operator other Literals.
inline bool operator==(const Literal<fields_...>& _other) const {
bool operator==(const Literal<fields_...>& _other) const {
return value() == _other.value();
}
/// Equality operator other Literals with different fields.
template <internal::StringLiteral... other_fields>
inline bool operator==(const Literal<other_fields...>& _other) const {
bool operator==(const Literal<other_fields...>& _other) const {
return name() == _other.name();
}
/// Inequality operator for other Literals.
template <internal::StringLiteral... other_fields>
inline bool operator!=(const Literal<other_fields...>& _other) const {
bool operator!=(const Literal<other_fields...>& _other) const {
return !(*this == _other);
}
/// Equality operator for strings.
inline bool operator==(const std::string& _str) const {
return name() == _str;
}
bool operator==(const std::string& _str) const { return name() == _str; }
/// Inequality operator for strings.
inline bool operator!=(const std::string& _str) const {
return name() != _str;
}
bool operator!=(const std::string& _str) const { return name() != _str; }
/// Alias for .name().
std::string str() const { return name(); }
/// Returns the value actually contained in the Literal.
inline ValueType value() const { return value_; }
ValueType value() const { return value_; }
/// Returns the value of the string literal in the template.
template <internal::StringLiteral _name>
@@ -187,7 +170,7 @@ class Literal {
/// Returns all of the allowed fields.
template <int _i = 0>
inline static std::string allowed_strings(const std::string& _values = "") {
static std::string allowed_strings(const std::string& _values = "") {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
const auto head = "'" + FieldType::field_.str() + "'";
const auto values = _values.size() == 0 ? head : _values + ", " + head;
@@ -200,7 +183,7 @@ class Literal {
/// Whether the Literal contains duplicate strings.
template <int _i = 1>
inline constexpr static bool has_duplicate_strings() {
constexpr static bool has_duplicate_strings() {
if constexpr (_i >= num_fields_) {
return false;
} else {
@@ -209,7 +192,7 @@ class Literal {
}
template <int _i, int _j = _i - 1>
inline constexpr static bool is_duplicate() {
constexpr static bool is_duplicate() {
using FieldType1 = typename std::tuple_element<_i, FieldsType>::type;
using FieldType2 = typename std::tuple_element<_j, FieldsType>::type;
if constexpr (FieldType1::field_ == FieldType2::field_) {
@@ -239,7 +222,7 @@ class Literal {
/// Finds the correct index associated with
/// the string at compile time within the Literal's own fields.
template <int _i>
inline constexpr static auto find_name_within_own_fields() {
constexpr static auto find_name_within_own_fields() {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
return FieldType::field_;
}
@@ -247,7 +230,7 @@ class Literal {
/// Finds the correct value associated with
/// the string at run time.
template <int _i = 0>
inline static Result<int> find_value(const std::string& _str) {
static Result<int> find_value(const std::string& _str) {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
if (FieldType::field_.str() == _str) {
return _i;
@@ -276,7 +259,7 @@ class Literal {
/// Whether the literal contains this string.
template <int _i = 0>
inline static bool has_value(const std::string& _str) {
static bool has_value(const std::string& _str) {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
if (FieldType::field_.str() == _str) {
return true;
+15 -56
View File
@@ -70,16 +70,10 @@ class NamedTuple {
}
/// Copy constructor.
NamedTuple(const NamedTuple<FieldTypes...>& _other)
: values_(_other.values_) {
// Duplicate field checks not required - has already been checked.
}
NamedTuple(const NamedTuple<FieldTypes...>& _other) = default;
/// Move constructor.
NamedTuple(NamedTuple<FieldTypes...>&& _other)
: values_(std::move(_other.values_)) {
// Duplicate field checks not required - has already been checked.
}
NamedTuple(NamedTuple<FieldTypes...>&& _other) = default;
/// Copy constructor.
template <class... OtherFieldTypes>
@@ -149,17 +143,6 @@ class NamedTuple {
}
}
/// Template specialization for std::tuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
auto add(const std::tuple<TupContent...>& _tuple, Tail&&... _tail) const {
if constexpr (sizeof...(Tail) > 0) {
return add_tuple(_tuple).add(std::forward<Tail>(_tail)...);
} else {
return add_tuple(std::forward<std::tuple<TupContent...>>(_tuple));
}
}
/// Template specialization for NamedTuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
@@ -178,21 +161,6 @@ class NamedTuple {
std::forward<Tail>(_tail)...);
}
/// Template specialization for NamedTuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
auto add(const NamedTuple<TupContent...>& _named_tuple, Tail&&... _tail) {
return add(_named_tuple.fields(), std::forward<Tail>(_tail)...);
}
/// Template specialization for NamedTuple, so we can pass fields from other
/// named tuples.
template <class... TupContent, class... Tail>
auto add(const NamedTuple<TupContent...>& _named_tuple,
Tail&&... _tail) const {
return add(_named_tuple.fields(), std::forward<Tail>(_tail)...);
}
/// Returns a tuple containing the fields.
Fields fields() { return make_fields(); }
@@ -201,62 +169,53 @@ class NamedTuple {
/// Gets a field by index.
template <int _index>
inline auto& get() {
auto& get() {
return rfl::get<_index>(*this);
}
/// Gets a field by name.
template <internal::StringLiteral _field_name>
inline auto& get() {
auto& get() {
return rfl::get<_field_name>(*this);
}
/// Gets a field by the field type.
template <class Field>
inline auto& get() {
auto& get() {
return rfl::get<Field>(*this);
}
/// Gets a field by index.
template <int _index>
inline const auto& get() const {
const auto& get() const {
return rfl::get<_index>(*this);
}
/// Gets a field by name.
template <internal::StringLiteral _field_name>
inline const auto& get() const {
const auto& get() const {
return rfl::get<_field_name>(*this);
}
/// Gets a field by the field type.
template <class Field>
inline const auto& get() const {
const auto& get() const {
return rfl::get<Field>(*this);
}
/// Returns the results wrapped in a field.
template <internal::StringLiteral _field_name>
inline auto get_field() const {
auto get_field() const {
return rfl::make_field<_field_name>(rfl::get<_field_name>(*this));
}
/// Copy assignment operator.
NamedTuple<FieldTypes...>& operator=(
const NamedTuple<FieldTypes...>& _other) {
values_ = _other.values_;
return *this;
}
const NamedTuple<FieldTypes...>& _other) = default;
/// Move assignment operator.
NamedTuple<FieldTypes...>& operator=(
NamedTuple<FieldTypes...>&& _other) noexcept {
if (this == &_other) {
return *this;
}
values_ = std::move(_other.values_);
return *this;
}
NamedTuple<FieldTypes...>&& _other) noexcept = default;
/// Replaces one or several fields, returning a new version
/// with the non-replaced fields left unchanged.
@@ -345,7 +304,7 @@ class NamedTuple {
template <class... TupContent>
constexpr auto add_tuple(std::tuple<TupContent...>&& _tuple) {
const auto a = [this](auto&&... _fields) {
return add(std::forward<TupContent>(_fields)...);
return this->add(std::forward<TupContent>(_fields)...);
};
return std::apply(a, std::forward<std::tuple<TupContent...>>(_tuple));
}
@@ -355,7 +314,7 @@ class NamedTuple {
template <class... TupContent>
constexpr auto add_tuple(std::tuple<TupContent...>&& _tuple) const {
const auto a = [this](auto&&... _fields) {
return add(std::forward<TupContent>(_fields)...);
return this->add(std::forward<TupContent>(_fields)...);
};
return std::apply(a, std::forward<std::tuple<TupContent...>>(_tuple));
}
@@ -458,7 +417,7 @@ class NamedTuple {
template <class... TupContent, size_t... Is>
auto replace_tuple(std::tuple<TupContent...>&& _tuple) {
const auto r = [this](auto&&... _fields) {
return replace(std::forward<TupContent>(_fields)...);
return this->replace(std::forward<TupContent>(_fields)...);
};
return std::apply(r, std::forward<std::tuple<TupContent...>>(_tuple));
}
@@ -468,7 +427,7 @@ class NamedTuple {
template <class... TupContent, size_t... Is>
auto replace_tuple(std::tuple<TupContent...>&& _tuple) const {
const auto r = [this](auto&&... _fields) {
return replace(std::forward<TupContent>(_fields)...);
return this->replace(std::forward<TupContent>(_fields)...);
};
return std::apply(r, std::forward<std::tuple<TupContent...>>(_tuple));
}
+10 -18
View File
@@ -18,9 +18,11 @@ class Ref {
return Ref<T>(std::make_shared<T>(std::forward<Args>(_args)...));
}
Ref(const Ref<T>& _other) : ptr_(_other.ptr_){};
Ref() : ptr_(std::make_shared<T>()) {}
Ref(Ref<T>&& _other) : ptr_(std::move(_other.ptr_)) {}
Ref(const Ref<T>& _other) = default;
Ref(Ref<T>&& _other) = default;
template <class Y>
Ref(const Ref<Y>& _other) : ptr_(_other.ptr()) {}
@@ -28,16 +30,16 @@ class Ref {
~Ref() = default;
/// Returns a pointer to the underlying object
inline T* get() const { return ptr_.get(); }
T* get() const { return ptr_.get(); }
/// Returns the underlying object.
inline T& operator*() const { return *ptr_; }
T& operator*() const { return *ptr_; }
/// Returns the underlying object.
inline T* operator->() const { return ptr_.get(); }
T* operator->() const { return ptr_.get(); }
/// Returns the underlying shared_ptr
inline const std::shared_ptr<T>& ptr() const { return ptr_; }
const std::shared_ptr<T>& ptr() const { return ptr_; }
/// Copy assignment operator.
template <class Y>
@@ -47,20 +49,10 @@ class Ref {
}
/// Move assignment operator
inline Ref<T>& operator=(Ref<T>&& _other) noexcept {
if (&_other != this) {
ptr_ = std::move(_other.ptr_);
}
return *this;
}
Ref<T>& operator=(Ref<T>&& _other) noexcept = default;
/// Copy assignment operator
inline Ref<T>& operator=(const Ref<T>& _other) {
if (&_other != this) {
ptr_ = _other.ptr_;
}
return *this;
}
Ref<T>& operator=(const Ref<T>& _other) = default;
private:
/// Only make is allowed to use this constructor.
+32 -21
View File
@@ -45,6 +45,14 @@ class Result {
Result(Error&& _err) noexcept : t_or_err_(std::move(_err)) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Result(Result<U>&& _other)
: t_or_err_(
std::forward<Result<U>>(_other)
.transform([](U&& _u) { return T(std::forward<U>(_u)); })
.t_or_err_) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Result(const Result<U>& _other)
@@ -144,7 +152,7 @@ class Result {
/// them within a std::range.
const T* end() const noexcept {
const auto get_ptr =
[this]<class TOrError>(const TOrError& _t_or_err) -> const T* {
[]<class TOrError>(const TOrError& _t_or_err) -> const T* {
if constexpr (!std::is_same<TOrError, Error>()) {
return &_t_or_err + 1;
} else {
@@ -158,7 +166,7 @@ class Result {
/// or std::nullopt otherwise.
std::optional<Error> error() const noexcept {
const auto get_err =
[this]<class TOrError>(
[]<class TOrError>(
const TOrError& _t_or_err) -> std::optional<Error> {
if constexpr (!std::is_same<TOrError, Error>()) {
return std::nullopt;
@@ -183,25 +191,15 @@ class Result {
const T& operator*() const { return *std::get_if<T>(&t_or_err_); }
/// Assigns the underlying object.
inline Result<T>& operator=(const Result<T>& _other) {
if (this != &_other) {
t_or_err_ = _other.t_or_err_;
}
return *this;
}
Result<T>& operator=(const Result<T>& _other) = default;
/// Assigns the underlying object.
inline Result<T>& operator=(Result<T>&& _other) {
if (this != &_other) {
t_or_err_ = std::move(_other.t_or_err_);
}
return *this;
}
Result<T>& operator=(Result<T>&& _other) = default;
/// Assigns the underlying object.
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
inline auto& operator=(const Result<U>& _other) {
auto& operator=(const Result<U>& _other) {
const auto to_t = [](const U& _u) -> T { return _u; };
t_or_err_ = _other.transform(to_t).t_or_err_;
return *this;
@@ -213,10 +211,10 @@ class Result {
Result<T> or_else(const F& _f) {
const auto handle_variant =
[&]<class TOrError>(TOrError&& _t_or_err) -> Result<T> {
if constexpr (std::is_same<TOrError, Error>()) {
return _f(std::forward<TOrError>(_t_or_err));
if constexpr (std::is_same<std::decay_t<TOrError>, Error>()) {
return _f(std::forward<Error>(_t_or_err));
} else {
return std::forward<TOrError>(_t_or_err);
return std::forward<T>(_t_or_err);
}
};
return std::visit(handle_variant,
@@ -284,11 +282,11 @@ class Result {
/// Returns the value if the result does not contain an error, throws an
/// exceptions if not. Similar to .unwrap() in Rust.
T& value() {
T value() {
const auto handle_variant =
[&]<class TOrError>(TOrError& _t_or_err) -> T& {
[&]<class TOrError>(TOrError& _t_or_err) -> T {
if constexpr (!std::is_same<TOrError, Error>()) {
return _t_or_err;
return std::forward<T>(_t_or_err);
} else {
throw std::runtime_error(_t_or_err.what());
}
@@ -310,6 +308,19 @@ class Result {
return std::visit(handle_variant, t_or_err_);
}
/// Returns the value or a default.
T value_or(const T& _default) noexcept {
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> T {
if constexpr (!std::is_same<TOrError, Error>()) {
return std::forward<T>(_t_or_err);
} else {
return _default;
}
};
return std::visit(handle_variant, t_or_err_);
}
/// Returns the value or a default.
T value_or(const T& _default) const noexcept {
const auto handle_variant =
+14 -26
View File
@@ -20,13 +20,11 @@ struct TaggedUnion {
TaggedUnion(VariantType&& _variant) noexcept
: variant_(std::move(_variant)) {}
TaggedUnion(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _tagged_union)
: variant_(_tagged_union.variant_) {}
TaggedUnion(const TaggedUnion<_discriminator, NamedTupleTypes...>&
_tagged_union) = default;
TaggedUnion(TaggedUnion<_discriminator, NamedTupleTypes...>&&
_tagged_union) noexcept
: variant_(std::move(_tagged_union.variant_)) {}
_tagged_union) noexcept = default;
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
@@ -41,14 +39,14 @@ struct TaggedUnion {
~TaggedUnion() = default;
/// Assigns the underlying object.
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
const VariantType& _variant) {
variant_ = _variant;
return *this;
}
/// Assigns the underlying object.
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
VariantType&& _variant) {
variant_ = std::move(_variant);
return *this;
@@ -58,8 +56,7 @@ struct TaggedUnion {
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
T&& _variant) {
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(T&& _variant) {
variant_ = std::forward<T>(_variant);
return *this;
}
@@ -68,35 +65,26 @@ struct TaggedUnion {
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
const T& _variant) {
variant_ = _variant;
return *this;
}
/// Assigns the underlying object.
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _other) {
if (this != &_other) {
variant_ = _other.get();
}
return *this;
}
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _other) =
default;
/// Assigns the underlying object.
inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
TaggedUnion<_discriminator, NamedTupleTypes...>&& _other) {
if (this != &_other) {
variant_ = std::move(_other.variant_);
}
return *this;
}
TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(
TaggedUnion<_discriminator, NamedTupleTypes...>&& _other) = default;
/// Returns the underlying variant.
inline VariantType& variant() { return variant_; }
VariantType& variant() { return variant_; }
/// Returns the underlying variant.
inline const VariantType& variant() const { return variant_; }
const VariantType& variant() const { return variant_; }
/// The underlying variant - a TaggedUnion is a thin wrapper
/// around a variant that is mainly used for parsing.
+5
View File
@@ -21,6 +21,11 @@ struct StringLiteral {
/// Returns the value as a string.
std::string str() const { return std::string(value_); }
/// Returns the value as a string.
std::string_view string_view() const {
return std::string_view(value_, N - 1);
}
};
template <size_t N1, size_t N2>
File diff suppressed because it is too large Load Diff
@@ -50,7 +50,7 @@ template <class T, class Pointers, class... Args>
auto move_from_pointers(Pointers& _ptrs, Args&&... _args) {
constexpr auto i = sizeof...(Args);
if constexpr (i == std::tuple_size_v<std::decay_t<Pointers>>) {
return T(std::move(_args)...);
return T{std::move(_args)...};
} else {
using FieldType = std::tuple_element_t<i, std::decay_t<Pointers>>;
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_LOAD_STRING_HPP_
#define RFL_IO_LOAD_STRING_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<std::string> load_string(const std::string& _fname) {
std::ifstream infile(_fname);
if (infile.is_open()) {
auto r = std::string(std::istreambuf_iterator<char>(infile),
std::istreambuf_iterator<char>());
infile.close();
return r;
} else {
return Error("Unable to open file '" + _fname +
"' or file could not be found.");
}
}
} // namespace io
} // namespace rfl
#endif
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_SAVE_STRING_HPP_
#define RFL_IO_SAVE_STRING_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<Nothing> save_string(const std::string& _fname,
const std::string& _str) {
try {
std::ofstream outfile;
outfile.open(_fname);
outfile << _str;
outfile.close();
} catch (std::exception& e) {
return Error(e.what());
}
return Nothing{};
}
} // namespace io
} // namespace rfl
#endif
+2
View File
@@ -4,7 +4,9 @@
#include "rfl/json/Parser.hpp"
#include "rfl/json/Reader.hpp"
#include "rfl/json/Writer.hpp"
#include "rfl/json/load.hpp"
#include "rfl/json/read.hpp"
#include "rfl/json/save.hpp"
#include "rfl/json/write.hpp"
#endif
+63 -50
View File
@@ -3,13 +3,16 @@
#include <yyjson.h>
#include <array>
#include <exception>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include "rfl/Result.hpp"
@@ -18,34 +21,20 @@
namespace rfl {
namespace json {
struct YYJSONOutputArray {
yyjson_mut_val* val_;
};
struct YYJSONOutputObject {
yyjson_mut_val* val_;
};
struct YYJSONOutputVar {
YYJSONOutputVar(yyjson_mut_val* _val) : val_(_val) {}
YYJSONOutputVar(YYJSONOutputArray _arr) : val_(_arr.val_) {}
YYJSONOutputVar(YYJSONOutputObject _obj) : val_(_obj.val_) {}
yyjson_mut_val* val_;
};
struct Reader {
struct YYJSONInputArray {
YYJSONInputArray(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputObject {
YYJSONInputObject(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputVar {
YYJSONInputVar() : val_(nullptr) {}
YYJSONInputVar(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
@@ -62,13 +51,18 @@ struct Reader {
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
static constexpr bool has_custom_constructor = has_from_json_obj<T>::value;
rfl::Result<InputVarType> get_field(const std::string& _name,
InputObjectType* _obj) const noexcept {
const auto var =
InputVarType(yyjson_obj_get(_obj->val_, _name.c_str()));
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str()));
if (!var.val_) {
return rfl::Error("Object contains no field named '" + _name +
"'.");
@@ -76,72 +70,90 @@ struct Reader {
return var;
}
bool is_empty(InputVarType* _var) const noexcept {
return !_var->val_ || yyjson_is_null(_var->val_);
bool is_empty(const InputVarType _var) const noexcept {
return !_var.val_ || yyjson_is_null(_var.val_);
}
template <class T>
rfl::Result<T> to_basic_type(InputVarType* _var) const noexcept {
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
const auto r = yyjson_get_str(_var->val_);
const auto r = yyjson_get_str(_var.val_);
if (r == NULL) {
return rfl::Error("Could not cast to string.");
}
return std::string(r);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!yyjson_is_bool(_var->val_)) {
if (!yyjson_is_bool(_var.val_)) {
return rfl::Error("Could not cast to boolean.");
}
return yyjson_get_bool(_var->val_);
return yyjson_get_bool(_var.val_);
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!yyjson_is_num(_var->val_)) {
if (!yyjson_is_num(_var.val_)) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(yyjson_get_num(_var->val_));
return static_cast<T>(yyjson_get_num(_var.val_));
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!yyjson_is_int(_var->val_)) {
if (!yyjson_is_int(_var.val_)) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_int(_var->val_));
return static_cast<T>(yyjson_get_int(_var.val_));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(InputVarType* _var) const noexcept {
if (!yyjson_is_arr(_var->val_)) {
rfl::Result<InputArrayType> to_array(
const InputVarType _var) const noexcept {
if (!yyjson_is_arr(_var.val_)) {
return rfl::Error("Could not cast to array!");
}
return InputArrayType(_var->val_);
return InputArrayType(_var.val_);
}
std::map<std::string, InputVarType> to_map(
InputObjectType* _obj) const noexcept {
std::map<std::string, InputVarType> m;
template <size_t size, class FunctionType>
std::array<InputVarType, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<InputVarType, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj->val_, &iter);
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const auto p =
std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace(std::move(p));
const char* k = yyjson_get_str(key);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_arr;
}
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
auto p = std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace_back(std::move(p));
}
return m;
}
rfl::Result<InputObjectType> to_object(InputVarType* _var) const noexcept {
if (!yyjson_is_obj(_var->val_)) {
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
if (!yyjson_is_obj(_var.val_)) {
return rfl::Error("Could not cast to object!");
}
return InputObjectType(_var->val_);
return InputObjectType(_var.val_);
}
std::vector<InputVarType> to_vec(InputArrayType* _arr) const noexcept {
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
std::vector<InputVarType> vec;
yyjson_val* val;
yyjson_arr_iter iter;
yyjson_arr_iter_init(_arr->val_, &iter);
yyjson_arr_iter_init(_arr.val_, &iter);
while ((val = yyjson_arr_iter_next(&iter))) {
vec.push_back(InputVarType(val));
}
@@ -149,9 +161,10 @@ struct Reader {
}
template <class T>
rfl::Result<T> use_custom_constructor(InputVarType* _var) const noexcept {
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
try {
return T::from_json_obj(*_var);
return T::from_json_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
+9 -4
View File
@@ -13,16 +13,19 @@
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
namespace rfl {
namespace json {
struct Writer {
struct YYJSONOutputArray {
YYJSONOutputArray(yyjson_mut_val* _val) : val_(_val) {}
yyjson_mut_val* val_;
};
struct YYJSONOutputObject {
YYJSONOutputObject(yyjson_mut_val* _val) : val_(_val) {}
yyjson_mut_val* val_;
};
@@ -53,7 +56,7 @@ struct Writer {
}
template <class T>
OutputVarType from_basic_type(const T _var) const noexcept {
OutputVarType from_basic_type(const T& _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
return OutputVarType(yyjson_mut_strcpy(doc_, _var.c_str()));
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
@@ -61,8 +64,10 @@ struct Writer {
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
return OutputVarType(
yyjson_mut_real(doc_, static_cast<double>(_var)));
} else {
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
return OutputVarType(yyjson_mut_int(doc_, static_cast<int>(_var)));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
@@ -74,8 +79,8 @@ struct Writer {
return OutputObjectType(yyjson_mut_obj(doc_));
}
bool is_empty(OutputVarType* _var) const noexcept {
return yyjson_mut_is_null(_var->val_);
bool is_empty(const OutputVarType& _var) const noexcept {
return yyjson_mut_is_null(_var.val_);
}
void set_field(const std::string& _name, const OutputVarType& _var,
+19
View File
@@ -0,0 +1,19 @@
#ifndef RFL_JSON_LOAD_HPP_
#define RFL_JSON_LOAD_HPP_
#include "rfl/Result.hpp"
#include "rfl/io/load_string.hpp"
#include "rfl/json/read.hpp"
namespace rfl {
namespace json {
template <class T>
Result<T> load(const std::string& _fname) {
return rfl::io::load_string(_fname).and_then(read<T>);
}
} // namespace json
} // namespace rfl
#endif
+8 -3
View File
@@ -14,15 +14,20 @@ namespace json {
using InputObjectType = typename Reader::InputObjectType;
using InputVarType = typename Reader::InputVarType;
/// Parses an object from a JSON var.
template <class T>
Result<T> read(const InputVarType& _obj) {
const auto r = Reader();
return Parser<T>::read(r, _obj);
}
/// Parses an object from JSON using reflection.
template <class T>
Result<T> read(const std::string& _json_str) {
using PtrType = std::unique_ptr<yyjson_doc, void (*)(yyjson_doc*)>;
yyjson_doc* doc = yyjson_read(_json_str.c_str(), _json_str.size(), 0);
const auto ptr = PtrType(doc, yyjson_doc_free);
InputVarType root = InputVarType(yyjson_doc_get_root(doc));
const auto r = Reader();
return Parser<T>::read(r, &root);
return read<T>(InputVarType(yyjson_doc_get_root(doc)));
}
} // namespace json
+23
View File
@@ -0,0 +1,23 @@
#ifndef RFL_JSON_SAVE_HPP_
#define RFL_JSON_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
#include "rfl/io/save_string.hpp"
#include "rfl/json/write.hpp"
namespace rfl {
namespace json {
template <class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
return rfl::io::save_string(write(_obj));
}
} // namespace json
} // namespace rfl
#endif
@@ -0,0 +1,16 @@
#ifndef RFL_PARSING_AREREADERANDWRITER_HPP_
#define RFL_PARSING_AREREADERANDWRITER_HPP_
#include "rfl/parsing/IsReader.hpp"
#include "rfl/parsing/IsWriter.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
concept AreReaderAndWriter = IsReader<R, T> && IsWriter<W, T>;
} // namespace parsing
} // namespace rfl
#endif
+1 -1
View File
@@ -15,7 +15,7 @@ template <class ReaderType, class WriterType, class OriginalClass,
class HelperStruct>
struct CustomParser {
static Result<OriginalClass> read(const ReaderType& _r,
auto* _var) noexcept {
const auto& _var) noexcept {
const auto to_class = [](auto&& _h) -> Result<OriginalClass> {
try {
if constexpr (internal::has_to_class_method_v<HelperStruct>) {
+83
View File
@@ -0,0 +1,83 @@
#ifndef RFL_PARSING_ISREADER_HPP_
#define RFL_PARSING_ISREADER_HPP_
#include <array>
#include <concepts>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include "rfl/Result.hpp"
namespace rfl {
namespace parsing {
template <class R, class T>
concept IsReader = requires(R r, std::string name,
std::function<std::int16_t(std::string_view)> fct,
typename R::InputArrayType arr,
typename R::InputObjectType obj,
typename R::InputVarType var) {
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Retrieves a particular field from an object.
{
r.get_field(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{ r.template to_basic_type<T>(var) } -> std::same_as<rfl::Result<T>>;
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
{
r.template to_fields_array<6>(fct, obj)
} -> std::same_as<std::array<typename R::InputVarType, 6>>;
/// Casts var as an InputArrayType.
{
r.to_array(var)
} -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
{
r.to_map(obj)
} -> std::same_as<
std::vector<std::pair<std::string, typename R::InputVarType>>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Iterates through an array and writes the contained vars into
/// a vector.
{ r.to_vec(arr) } -> std::same_as<std::vector<typename R::InputVarType>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{
r.template use_custom_constructor<T>(var)
} -> std::same_as<rfl::Result<T>>;
};
} // namespace parsing
} // namespace rfl
#endif
+50
View File
@@ -0,0 +1,50 @@
#ifndef RFL_PARSING_ISWRITER_HPP_
#define RFL_PARSING_ISWRITER_HPP_
#include <concepts>
#include "rfl/Result.hpp"
namespace rfl {
namespace parsing {
template <class W, class T>
concept IsWriter = requires(W w, T t, std::string name,
typename W::OutputArrayType arr,
typename W::OutputObjectType obj,
typename W::OutputVarType var) {
/// Any Writer needs to define the following:
///
/// 1) An OutputArrayType, which must be an array-like data structure.
/// 2) An OutputObjectType, which must contain key-value pairs.
/// 3) An OutputVarType, which must be able to represent either
/// OutputArrayType, OutputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// Appends var to the end of arr, thus mutating it.
{ w.add(var, &arr) } -> std::same_as<void>;
/// Returns an empty var (usually the NULL type).
{ w.empty_var() } -> std::same_as<typename W::OutputVarType>;
/// Generates a var from a basic type (std::string, bool, floating point or
/// integral).
{ w.from_basic_type(t) } -> std::same_as<typename W::OutputVarType>;
/// Generates a new, empty array.
{ w.new_array() } -> std::same_as<typename W::OutputArrayType>;
/// Generates a new, empty object.
{ w.new_object() } -> std::same_as<typename W::OutputObjectType>;
/// Determines whether the var is empty (the NULL type).
{ w.is_empty(var) } -> std::same_as<bool>;
/// Adds a new field to obj, thus mutating it.
{ w.set_field(name, var, &obj) } -> std::same_as<void>;
};
} // namespace parsing
} // namespace rfl
#endif
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
#ifndef RFL_PARSING_IS_FORWARD_LIST_HPP_
#define RFL_PARSING_IS_FORWARD_LIST_HPP_
#include <forward_list>
#include <type_traits>
namespace rfl {
namespace parsing {
template <class T>
class is_forward_list;
template <class T>
class is_forward_list : public std::false_type {};
template <class T>
class is_forward_list<std::forward_list<T>> : public std::true_type {};
} // namespace parsing
} // namespace rfl
#endif
+32
View File
@@ -0,0 +1,32 @@
#ifndef RFL_PARSING_IS_MAP_LIKE_HPP_
#define RFL_PARSING_IS_MAP_LIKE_HPP_
#include <map>
#include <type_traits>
#include <unordered_map>
namespace rfl {
namespace parsing {
template <class T>
class is_map_like;
template <class T>
class is_map_like : public std::false_type {};
template <class K, class V>
class is_map_like<std::map<K, V>> : public std::true_type {};
template <class K, class V>
class is_map_like<std::multimap<K, V>> : public std::true_type {};
template <class K, class V>
class is_map_like<std::unordered_map<K, V>> : public std::true_type {};
template <class K, class V>
class is_map_like<std::unordered_multimap<K, V>> : public std::true_type {};
} // namespace parsing
} // namespace rfl
#endif
+32
View File
@@ -0,0 +1,32 @@
#ifndef RFL_PARSING_IS_SET_LIKE_HPP_
#define RFL_PARSING_IS_SET_LIKE_HPP_
#include <set>
#include <type_traits>
#include <unordered_set>
namespace rfl {
namespace parsing {
template <class T>
class is_set_like;
template <class T>
class is_set_like : public std::false_type {};
template <class T>
class is_set_like<std::set<T>> : public std::true_type {};
template <class T>
class is_set_like<std::unordered_set<T>> : public std::true_type {};
template <class T>
class is_set_like<std::multiset<T>> : public std::true_type {};
template <class T>
class is_set_like<std::unordered_multiset<T>> : public std::true_type {};
} // namespace parsing
} // namespace rfl
#endif
+4 -4
View File
@@ -32,10 +32,10 @@ void test_box() {
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node =
DecisionTree::Node{.critical_value = 10.0,
.lesser = rfl::make_box<DecisionTree>(leaf1),
.greater = rfl::make_box<DecisionTree>(leaf2)};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = rfl::make_box<DecisionTree>(DecisionTree{leaf1}),
.greater = rfl::make_box<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
+52
View File
@@ -0,0 +1,52 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
// Makes sure that the example in the README works as expected.
// It would be embarrassing if it didn't...
void test_custom_constructor() {
std::cout << "test_custom_constructor" << std::endl;
struct Person {
static rfl::Result<Person> from_json_obj(
typename rfl::json::Reader::InputVarType _obj) {
/// This only exists for the purpose of the test.
const auto change_first_name = [](auto&& _person) {
return rfl::replace(
std::move(_person),
rfl::Field<"firstName", std::string>("Bart"));
};
const auto from_nt = [](auto&& _nt) {
return rfl::from_named_tuple<Person>(std::move(_nt));
};
return rfl::json::read<rfl::named_tuple_t<Person>>(_obj)
.transform(from_nt)
.transform(change_first_name);
}
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
};
const auto res = rfl::json::read<Person>(
R"({"firstName":"Homer","lastName":"Simpson","birthday":"1987-04-19"})");
if (!res) {
std::cout << "Test failed on read. Error: "
<< res.error().value().what() << std::endl;
return;
}
if (res.value().first_name() != "Bart") {
std::cout << "Expected 'Bart', got '" << res.value().first_name() << "'"
<< std::endl
<< std::endl;
} else {
std::cout << "OK" << std::endl << std::endl;
}
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_deque() {
std::cout << "test_deque" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::deque<Person>>> children =
rfl::default_value;
};
auto children = std::make_unique<std::deque<Person>>();
children->emplace_back(Person{.first_name = "Bart"});
children->emplace_back(Person{.first_name = "Lisa"});
children->emplace_back(Person{.first_name = "Maggie"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})");
}
+42
View File
@@ -0,0 +1,42 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_error_messages() {
std::cout << "test_error_messages" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Field<"children", std::vector<Person>> children;
};
const std::string faulty_string =
R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})";
const auto result = rfl::json::read<Person>(faulty_string);
const std::string expected = R"(Found 3 errors:
1) Failed to parse field 'lastName': Could not cast to string.
2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'.
3) Field named 'children' not found.)";
if (!result.error()) {
std::cout << "Expected an error, got none." << std::endl << std::endl;
}
if (result.error().value().what() != expected) {
std::cout << "Expected: " << std::endl
<< expected << std::endl
<< "Got:" << std::endl
<< result.error().value().what() << std::endl
<< std::endl;
}
std::cout << "OK" << std::endl << std::endl;
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_forward_list() {
std::cout << "test_forward_list" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::forward_list<Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::forward_list<Person>>();
children->emplace_front(Person{.first_name = "Maggie"});
children->emplace_front(Person{.first_name = "Lisa"});
children->emplace_front(Person{.first_name = "Bart"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})");
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_list() {
std::cout << "test_list" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::list<Person>>> children =
rfl::default_value;
};
auto children = std::make_unique<std::list<Person>>();
children->emplace_back(Person{.first_name = "Bart"});
children->emplace_back(Person{.first_name = "Lisa"});
children->emplace_back(Person{.first_name = "Maggie"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})");
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include "write_and_read.hpp"
void test_map() {
std::cout << "test_map" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::map<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::map<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]]})");
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include "write_and_read.hpp"
void test_multimap() {
std::cout << "test_multimap" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::multimap<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::multimap<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]]})");
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_multiset() {
std::cout << "test_multiset" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::multiset<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::multiset<std::string>>(
std::multiset<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":["Bart","Lisa","Maggie"]})");
}
+4 -4
View File
@@ -32,10 +32,10 @@ void test_ref() {
const auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node =
DecisionTree::Node{.critical_value = 10.0,
.lesser = rfl::make_ref<DecisionTree>(leaf1),
.greater = rfl::make_ref<DecisionTree>(leaf2)};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = rfl::make_ref<DecisionTree>(DecisionTree{leaf1}),
.greater = rfl::make_ref<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_set() {
std::cout << "test_set" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::set<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::set<std::string>>(
std::set<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","children":["Bart","Lisa","Maggie"]})");
}
+20
View File
@@ -0,0 +1,20 @@
#include <iostream>
#include <map>
#include <memory>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include "write_and_read.hpp"
void test_string_map() {
std::cout << "test_string_map" << std::endl;
std::map<std::string, std::unique_ptr<std::string>> homer;
homer.insert(
std::make_pair("firstName", std::make_unique<std::string>("Homer")));
homer.insert(
std::make_pair("lastName", std::make_unique<std::string>("Simpson")));
write_and_read(homer, R"({"firstName":"Homer","lastName":"Simpson"})");
}
+25
View File
@@ -0,0 +1,25 @@
#include <iostream>
#include <memory>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <unordered_map>
#include "write_and_read.hpp"
void test_string_unordered_map() {
std::cout << "test_string_unordered_map" << std::endl;
using Map = std::unordered_map<std::string, std::unique_ptr<std::string>>;
Map homer;
homer.insert(
std::make_pair("firstName", std::make_unique<std::string>("Homer")));
homer.insert(
std::make_pair("lastName", std::make_unique<std::string>("Simpson")));
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::json::write(homer);
const auto homer2 = rfl::json::read<Map>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+4 -4
View File
@@ -32,10 +32,10 @@ void test_unique_ptr2() {
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node =
DecisionTree::Node{.critical_value = 10.0,
.lesser = std::make_unique<DecisionTree>(leaf1),
.greater = std::make_unique<DecisionTree>(leaf2)};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = std::make_unique<DecisionTree>(DecisionTree{leaf1}),
.greater = std::make_unique<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
+32
View File
@@ -0,0 +1,32 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <unordered_map>
#include "write_and_read.hpp"
void test_unordered_map() {
std::cout << "test_unordered_map" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::unordered_map<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_map<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::json::write(homer);
const auto homer2 = rfl::json::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+33
View File
@@ -0,0 +1,33 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include "write_and_read.hpp"
void test_unordered_multimap() {
std::cout << "test_unordered_multimap" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children",
std::unique_ptr<std::unordered_multimap<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_multimap<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::json::write(homer);
const auto homer2 = rfl::json::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+31
View File
@@ -0,0 +1,31 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unordered_multiset() {
std::cout << "test_unordered_multiset" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children",
std::unique_ptr<std::unordered_multiset<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_multiset<std::string>>(
std::unordered_multiset<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered multisets are unpredictable. We therefore only make sure that
// this compiles.
const auto json_string = rfl::json::write(homer);
const auto homer2 = rfl::json::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unordered_set() {
std::cout << "test_unordered_set" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::unordered_set<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_set<std::string>>(
std::unordered_set<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered sets are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::json::write(homer);
const auto homer2 = rfl::json::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+27
View File
@@ -6,16 +6,27 @@
#include "test_custom_class2.hpp"
#include "test_custom_class3.hpp"
#include "test_custom_class4.hpp"
#include "test_custom_constructor.hpp"
#include "test_default_values.hpp"
#include "test_deque.hpp"
#include "test_error_messages.hpp"
#include "test_field_variant.hpp"
#include "test_flatten.hpp"
#include "test_forward_list.hpp"
#include "test_list.hpp"
#include "test_literal.hpp"
#include "test_map.hpp"
#include "test_multimap.hpp"
#include "test_multiset.hpp"
#include "test_optional_fields.hpp"
#include "test_readme_example.hpp"
#include "test_ref.hpp"
#include "test_replace.hpp"
#include "test_replace_flatten.hpp"
#include "test_replace_with_other_struct.hpp"
#include "test_set.hpp"
#include "test_string_map.hpp"
#include "test_string_unordered_map.hpp"
#include "test_tagged_union.hpp"
#include "test_timestamp.hpp"
#include "test_unique_ptr.hpp"
@@ -38,6 +49,20 @@ int main() {
test_array();
test_timestamp();
test_flatten();
test_deque();
test_forward_list();
test_list();
test_map();
test_unordered_map();
test_set();
test_unordered_set();
test_multimap();
test_unordered_multimap();
test_multiset();
test_unordered_multiset();
test_string_map();
test_string_unordered_map();
test_error_messages();
test_custom_class1();
test_custom_class2();
@@ -51,5 +76,7 @@ int main() {
test_as_flatten();
test_constr();
test_custom_constructor();
return 0;
}