diff --git a/README.md b/README.md index 8fa70e5a..2bd502d7 100644 --- a/README.md +++ b/README.md @@ -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(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. diff --git a/docs/README.md b/docs/README.md index 649a67f6..2d6e57ee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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. + diff --git a/docs/custom_parser.md b/docs/custom_parser.md index 83f1a1c2..1a045a12 100644 --- a/docs/custom_parser.md +++ b/docs/custom_parser.md @@ -96,7 +96,7 @@ const auto people = rfl::json::read>(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 { diff --git a/docs/json.md b/docs/json.md new file mode 100644 index 00000000..cc24e5f0 --- /dev/null +++ b/docs/json.md @@ -0,0 +1,81 @@ +# JSON + +For JSON support, you must also include the header ``. + +## 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> children; +}; +``` + +You can parse JSON strings like this: + +```cpp +const rfl::Result result = rfl::json::read(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 result = rfl::json::load("/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 from_json_obj(const JSONVar& _obj); +}; +``` + +And in your source file, you implement `from_json_obj` as follows: + +```cpp +rfl::Result Person::from_json_obj(const JSONVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::json::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the JSON parsing when the +source file is compiled. + diff --git a/docs/named_tuple.md b/docs/named_tuple.md new file mode 100644 index 00000000..406c568d --- /dev/null +++ b/docs/named_tuple.md @@ -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> 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>; + +using Rectangle = rfl::NamedTuple< + rfl::Field<"height", double>, + rfl::Field<"width", double>>; + +using Square rfl::NamedTuple>; + +// Untagged variant - OK +using Shapes = std::variant; + +// Externally tagged variant - also OK: +using Shapes = std::variant, + 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(a, b); +``` + +However, you do not really have to use `rfl::as` here. This will work as well: + +```cpp +// Same as rfl::as(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; + +// 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(bart_nt); +const auto bart_struct = rfl::from_named_tuple(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. + + + + diff --git a/docs/result.md b/docs/result.md new file mode 100644 index 00000000..8e22cc05 --- /dev/null +++ b/docs/result.md @@ -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(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(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(...)` checks whether these requirements are met. +If the requirements are met, `rfl::json::read` 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` contains a type `T`, +thenĀ `r.transform(f)` *will* return an `rfl::Result` containing a type `U`, otherwise it will return an `rfl::Result` +containing an error. + +`.and_then(...)` requires a function `F` of the type `T -> rfl::Result`. If the `rfl::Result` contains a type `T`, +thenĀ `r.and_then(f)` *might* return an `rfl::Result` 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` 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` (note that this is somewhat simplified): + +```cpp +const auto to_ptr = [](auto&& _t) { + return std::make_unique(std::move(_t)); +}; + +return Parser::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 +Result load(const std::string& _fname) { + return rfl::io::load_string(_fname).and_then(read); +} +``` + +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`. 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` 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`. + +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`. 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`. 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 { + return Error("Failed to parse field '" + key + "': " + _e.what()); +}; +return Parser::read(_r, &_var).or_else(embellish_error); +``` + +`r1.or_other(r2)` expects an `r2` or type `rfl::Result`. It returns an `r1`, if `r1` does not contain an error and `r2` otherwise. + diff --git a/docs/standard_containers.md b/docs/standard_containers.md new file mode 100644 index 00000000..bd8bb819 --- /dev/null +++ b/docs/standard_containers.md @@ -0,0 +1,41 @@ +# Support for standard containers + +The serialization and deserialization of containers is handled as follows: + +`std::map` and `std::unordered_map` are treated +as objects. + +Consider the following map: + +```cpp +std::map 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 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"}]] +``` + diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md new file mode 100644 index 00000000..1b7d7537 --- /dev/null +++ b/docs/supporting_your_own_format.md @@ -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 +using YourParser = rfl::parsing::Parser; +``` + +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 +rfl::Result 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::read(r, root); +} + +template +std::string write(const T& _obj) { + // You can pass variables to the constructor, if necessary + auto w = Writer(...); + + OutputVarType var = Parser::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 + 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`, 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 + 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 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 + rfl::Result 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 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 + std::array 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> 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 to_object( + const InputVarType& _var) const noexcept {...} + + /// Iterates through an array and writes the contained values into + /// a std::vector. + std::vector 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 + rfl::Result 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> children; +}; +``` + +This struct contains four fields. `rfl::parsing::Parser` expects `to_fields_array` +to return an `std::array` 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`. + diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index bb628334..6efd45c3 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -18,34 +18,50 @@ class Box { return Box(std::make_unique(std::forward(_args)...)); } + Box() : ptr_(std::make_unique()) {} + Box(const Box& _other) = delete; - Box(Box&& _other) : ptr_(std::move(_other.ptr_)) {} + Box(Box&& _other) = default; + + template , + bool>::type = true> + Box(Box&& _other) noexcept + : ptr_(std::make_unique(std::forward(*_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& operator=(const Box& _other) = delete; + Box& operator=(const Box& _other) = delete; /// Move assignment operator - inline Box& operator=(Box&& _other) noexcept { - if (&_other != this) { - ptr_ = std::move(_other.ptr_); - } + Box& operator=(Box&& _other) noexcept = default; + + /// Move assignment operator + template , + bool>::type = true> + Box& operator=(Box&& _other) noexcept { + ptr_ = std::make_unique(std::forward(*_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& ptr() const { return ptr_; } + const std::unique_ptr& ptr() const { return ptr_; } private: /// Only make is allowed to use this constructor. @@ -62,6 +78,18 @@ Box make_box(Args&&... _args) { return Box::make(std::forward(_args)...); } +template +inline auto operator<=>(const Box& _t1, const Box& _t2) { + return _t1.ptr() <=> _t2.ptr(); +} + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& _os, const Box& _b) { + _os << _b.get(); + return _os; +} + } // namespace rfl #endif diff --git a/include/rfl/Field.hpp b/include/rfl/Field.hpp index 2a19a923..77249f76 100644 --- a/include/rfl/Field.hpp +++ b/include/rfl/Field.hpp @@ -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 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 , 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 , 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 - 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 - inline auto& operator=(Field<_name, T>&& _field) { + auto& operator=(Field<_name, T>&& _field) { value_ = std::forward(_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_; diff --git a/include/rfl/Flatten.hpp b/include/rfl/Flatten.hpp index ca13d944..5d7028e8 100644 --- a/include/rfl/Flatten.hpp +++ b/include/rfl/Flatten.hpp @@ -19,10 +19,9 @@ struct Flatten { Flatten(Type&& _value) noexcept : value_(std::forward(_value)) {} - Flatten(const Flatten<_Type>& _f) : value_(_f.get()) {} + Flatten(const Flatten<_Type>& _f) = default; - Flatten(Flatten<_Type>&& _f) noexcept - : value_(std::forward(_f.value_)) {} + Flatten(Flatten<_Type>&& _f) noexcept = default; template Flatten(const Flatten& _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(_value); return *this; } @@ -64,46 +63,35 @@ struct Flatten { /// Assigns the underlying object. template , 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 - inline Flatten<_Type>& operator=(const Flatten& _f) { + Flatten<_Type>& operator=(const Flatten& _f) { value_ = _f.get(); return *this; } /// Assigns the underlying object. template - inline Flatten<_Type>& operator=(Flatten&& _f) { + Flatten<_Type>& operator=(Flatten&& _f) { value_ = std::forward(_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(_value); } + void set(Type&& _value) { value_ = std::forward(_value); } /// The underlying value. Type value_; diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index f1019fd5..9661f3f5 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -34,10 +34,10 @@ class Literal { static constexpr ValueType num_fields_ = sizeof...(fields_); /// Constructs a Literal from another literal. - Literal(const Literal& _other) : value_(_other.value_) {} + Literal(const Literal& _other) = default; /// Constructs a Literal from another literal. - Literal(Literal&& _other) noexcept : value_(_other.value_) {} + Literal(Literal&& _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 - 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 - 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 - 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 - inline constexpr static auto name_of() { + constexpr static auto name_of() { constexpr auto name = find_name_within_own_fields<_value>(); return Literal(); } /// Assigns from another literal. - Literal& operator=(const Literal& _other) { - if (this != &_other) { - value_ = _other.value_; - } - return *this; - } + Literal& operator=(const Literal& _other) = default; /// Assigns from another literal. - Literal& operator=(Literal&& _other) noexcept { - if (this != &_other) { - value_ = _other.value_; - } - return *this; - } + Literal& operator=(Literal&& _other) noexcept = + default; /// Assigns the literal from a string Literal& operator=(const std::string& _str) { @@ -141,37 +128,33 @@ class Literal { } /// Equality operator other Literals. - inline bool operator==(const Literal& _other) const { + bool operator==(const Literal& _other) const { return value() == _other.value(); } /// Equality operator other Literals with different fields. template - inline bool operator==(const Literal& _other) const { + bool operator==(const Literal& _other) const { return name() == _other.name(); } /// Inequality operator for other Literals. template - inline bool operator!=(const Literal& _other) const { + bool operator!=(const Literal& _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 @@ -187,7 +170,7 @@ class Literal { /// Returns all of the allowed fields. template - 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 - 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 - 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 - 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 - inline static Result find_value(const std::string& _str) { + static Result 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 - 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; diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 14f7f811..350e0f4e 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -70,16 +70,10 @@ class NamedTuple { } /// Copy constructor. - NamedTuple(const NamedTuple& _other) - : values_(_other.values_) { - // Duplicate field checks not required - has already been checked. - } + NamedTuple(const NamedTuple& _other) = default; /// Move constructor. - NamedTuple(NamedTuple&& _other) - : values_(std::move(_other.values_)) { - // Duplicate field checks not required - has already been checked. - } + NamedTuple(NamedTuple&& _other) = default; /// Copy constructor. template @@ -149,17 +143,6 @@ class NamedTuple { } } - /// Template specialization for std::tuple, so we can pass fields from other - /// named tuples. - template - auto add(const std::tuple& _tuple, Tail&&... _tail) const { - if constexpr (sizeof...(Tail) > 0) { - return add_tuple(_tuple).add(std::forward(_tail)...); - } else { - return add_tuple(std::forward>(_tuple)); - } - } - /// Template specialization for NamedTuple, so we can pass fields from other /// named tuples. template @@ -178,21 +161,6 @@ class NamedTuple { std::forward(_tail)...); } - /// Template specialization for NamedTuple, so we can pass fields from other - /// named tuples. - template - auto add(const NamedTuple& _named_tuple, Tail&&... _tail) { - return add(_named_tuple.fields(), std::forward(_tail)...); - } - - /// Template specialization for NamedTuple, so we can pass fields from other - /// named tuples. - template - auto add(const NamedTuple& _named_tuple, - Tail&&... _tail) const { - return add(_named_tuple.fields(), std::forward(_tail)...); - } - /// Returns a tuple containing the fields. Fields fields() { return make_fields(); } @@ -201,62 +169,53 @@ class NamedTuple { /// Gets a field by index. template - inline auto& get() { + auto& get() { return rfl::get<_index>(*this); } /// Gets a field by name. template - inline auto& get() { + auto& get() { return rfl::get<_field_name>(*this); } /// Gets a field by the field type. template - inline auto& get() { + auto& get() { return rfl::get(*this); } /// Gets a field by index. template - inline const auto& get() const { + const auto& get() const { return rfl::get<_index>(*this); } /// Gets a field by name. template - inline const auto& get() const { + const auto& get() const { return rfl::get<_field_name>(*this); } /// Gets a field by the field type. template - inline const auto& get() const { + const auto& get() const { return rfl::get(*this); } /// Returns the results wrapped in a field. template - inline auto get_field() const { + auto get_field() const { return rfl::make_field<_field_name>(rfl::get<_field_name>(*this)); } /// Copy assignment operator. NamedTuple& operator=( - const NamedTuple& _other) { - values_ = _other.values_; - return *this; - } + const NamedTuple& _other) = default; /// Move assignment operator. NamedTuple& operator=( - NamedTuple&& _other) noexcept { - if (this == &_other) { - return *this; - } - values_ = std::move(_other.values_); - return *this; - } + NamedTuple&& _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 constexpr auto add_tuple(std::tuple&& _tuple) { const auto a = [this](auto&&... _fields) { - return add(std::forward(_fields)...); + return this->add(std::forward(_fields)...); }; return std::apply(a, std::forward>(_tuple)); } @@ -355,7 +314,7 @@ class NamedTuple { template constexpr auto add_tuple(std::tuple&& _tuple) const { const auto a = [this](auto&&... _fields) { - return add(std::forward(_fields)...); + return this->add(std::forward(_fields)...); }; return std::apply(a, std::forward>(_tuple)); } @@ -458,7 +417,7 @@ class NamedTuple { template auto replace_tuple(std::tuple&& _tuple) { const auto r = [this](auto&&... _fields) { - return replace(std::forward(_fields)...); + return this->replace(std::forward(_fields)...); }; return std::apply(r, std::forward>(_tuple)); } @@ -468,7 +427,7 @@ class NamedTuple { template auto replace_tuple(std::tuple&& _tuple) const { const auto r = [this](auto&&... _fields) { - return replace(std::forward(_fields)...); + return this->replace(std::forward(_fields)...); }; return std::apply(r, std::forward>(_tuple)); } diff --git a/include/rfl/Ref.hpp b/include/rfl/Ref.hpp index 229ec0ce..90f2ba50 100644 --- a/include/rfl/Ref.hpp +++ b/include/rfl/Ref.hpp @@ -18,9 +18,11 @@ class Ref { return Ref(std::make_shared(std::forward(_args)...)); } - Ref(const Ref& _other) : ptr_(_other.ptr_){}; + Ref() : ptr_(std::make_shared()) {} - Ref(Ref&& _other) : ptr_(std::move(_other.ptr_)) {} + Ref(const Ref& _other) = default; + + Ref(Ref&& _other) = default; template Ref(const Ref& _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& ptr() const { return ptr_; } + const std::shared_ptr& ptr() const { return ptr_; } /// Copy assignment operator. template @@ -47,20 +49,10 @@ class Ref { } /// Move assignment operator - inline Ref& operator=(Ref&& _other) noexcept { - if (&_other != this) { - ptr_ = std::move(_other.ptr_); - } - return *this; - } + Ref& operator=(Ref&& _other) noexcept = default; /// Copy assignment operator - inline Ref& operator=(const Ref& _other) { - if (&_other != this) { - ptr_ = _other.ptr_; - } - return *this; - } + Ref& operator=(const Ref& _other) = default; private: /// Only make is allowed to use this constructor. diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index d12b6b19..2c84ffc4 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -45,6 +45,14 @@ class Result { Result(Error&& _err) noexcept : t_or_err_(std::move(_err)) {} + template , + bool>::type = true> + Result(Result&& _other) + : t_or_err_( + std::forward>(_other) + .transform([](U&& _u) { return T(std::forward(_u)); }) + .t_or_err_) {} + template , bool>::type = true> Result(const Result& _other) @@ -144,7 +152,7 @@ class Result { /// them within a std::range. const T* end() const noexcept { const auto get_ptr = - [this](const TOrError& _t_or_err) -> const T* { + [](const TOrError& _t_or_err) -> const T* { if constexpr (!std::is_same()) { return &_t_or_err + 1; } else { @@ -158,7 +166,7 @@ class Result { /// or std::nullopt otherwise. std::optional error() const noexcept { const auto get_err = - [this]( + []( const TOrError& _t_or_err) -> std::optional { if constexpr (!std::is_same()) { return std::nullopt; @@ -183,25 +191,15 @@ class Result { const T& operator*() const { return *std::get_if(&t_or_err_); } /// Assigns the underlying object. - inline Result& operator=(const Result& _other) { - if (this != &_other) { - t_or_err_ = _other.t_or_err_; - } - return *this; - } + Result& operator=(const Result& _other) = default; /// Assigns the underlying object. - inline Result& operator=(Result&& _other) { - if (this != &_other) { - t_or_err_ = std::move(_other.t_or_err_); - } - return *this; - } + Result& operator=(Result&& _other) = default; /// Assigns the underlying object. template , bool>::type = true> - inline auto& operator=(const Result& _other) { + auto& operator=(const Result& _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 or_else(const F& _f) { const auto handle_variant = [&](TOrError&& _t_or_err) -> Result { - if constexpr (std::is_same()) { - return _f(std::forward(_t_or_err)); + if constexpr (std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); } else { - return std::forward(_t_or_err); + return std::forward(_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 = - [&](TOrError& _t_or_err) -> T& { + [&](TOrError& _t_or_err) -> T { if constexpr (!std::is_same()) { - return _t_or_err; + return std::forward(_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 = + [&](const TOrError& _t_or_err) -> T { + if constexpr (!std::is_same()) { + return std::forward(_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 = diff --git a/include/rfl/TaggedUnion.hpp b/include/rfl/TaggedUnion.hpp index c832c456..7d3a9d8b 100644 --- a/include/rfl/TaggedUnion.hpp +++ b/include/rfl/TaggedUnion.hpp @@ -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 , @@ -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 , bool>::type = true> - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( - T&& _variant) { + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(T&& _variant) { variant_ = std::forward(_variant); return *this; } @@ -68,35 +65,26 @@ struct TaggedUnion { template , 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. diff --git a/include/rfl/internal/StringLiteral.hpp b/include/rfl/internal/StringLiteral.hpp index daa7a046..c5cfc7b2 100644 --- a/include/rfl/internal/StringLiteral.hpp +++ b/include/rfl/internal/StringLiteral.hpp @@ -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 diff --git a/include/rfl/internal/has_n_fields.hpp b/include/rfl/internal/has_n_fields.hpp index e1dcbf9b..625fbeef 100644 --- a/include/rfl/internal/has_n_fields.hpp +++ b/include/rfl/internal/has_n_fields.hpp @@ -7,1022 +7,26 @@ namespace rfl { namespace internal { -template -concept aggregate = std::is_aggregate_v; - -template -concept constructable = aggregate && requires { - T{std::declval()...}; -}; - struct any { template constexpr operator T() const noexcept; }; -template -struct constructable_with_n_fields; +template +struct constructible_with_n_fields_impl : std::false_type {}; -/*The following boilerplate code was generated using a Python script: +template +struct constructible_with_n_fields_impl< + T, std::index_sequence, + std::void_t> : std::true_type {}; -def has_field_template(num: int) -> str: - anys = "".join([", any"] * num) - return """ - template - struct constructable_with_n_fields { - static constexpr bool value = constructable; - }; - """.replace( - "{num}", str(num) - ).replace( - "{anys}", anys - ) +template +using constructible_with_n_fields = + constructible_with_n_fields_impl>; - -code = "".join((has_field_template(i) for i in range(102))) -with open("generated_code.cpp", "w", encoding="utf-8") as codefile: - codefile.write(code) - -*/ - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any>; -}; - -// --------------------------------- -// End of generated boilerplate code -// --------------------------------- - -template -constexpr bool has_n_fields = constructable_with_n_fields::value && - !constructable_with_n_fields::value; +template +constexpr bool has_n_fields = constructible_with_n_fields::value && + !constructible_with_n_fields::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/move_from_named_tuple.hpp b/include/rfl/internal/move_from_named_tuple.hpp index 8f09a016..821c5c0b 100644 --- a/include/rfl/internal/move_from_named_tuple.hpp +++ b/include/rfl/internal/move_from_named_tuple.hpp @@ -50,7 +50,7 @@ template auto move_from_pointers(Pointers& _ptrs, Args&&... _args) { constexpr auto i = sizeof...(Args); if constexpr (i == std::tuple_size_v>) { - return T(std::move(_args)...); + return T{std::move(_args)...}; } else { using FieldType = std::tuple_element_t>; diff --git a/include/rfl/io/load_string.hpp b/include/rfl/io/load_string.hpp new file mode 100644 index 00000000..4a8c28d0 --- /dev/null +++ b/include/rfl/io/load_string.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_LOAD_STRING_HPP_ +#define RFL_IO_LOAD_STRING_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result load_string(const std::string& _fname) { + std::ifstream infile(_fname); + if (infile.is_open()) { + auto r = std::string(std::istreambuf_iterator(infile), + std::istreambuf_iterator()); + infile.close(); + return r; + } else { + return Error("Unable to open file '" + _fname + + "' or file could not be found."); + } +} + +} // namespace io +} // namespace rfl + +#endif diff --git a/include/rfl/io/save_string.hpp b/include/rfl/io/save_string.hpp new file mode 100644 index 00000000..dcef60ed --- /dev/null +++ b/include/rfl/io/save_string.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_SAVE_STRING_HPP_ +#define RFL_IO_SAVE_STRING_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result 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 diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index 9dce6813..bc8cec2a 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -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 diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index 7a3e5ba8..bb091643 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -3,13 +3,16 @@ #include +#include #include #include +#include #include #include #include #include #include +#include #include #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 + struct has_from_json_obj, decltype(T::from_json_obj), + typename Reader::InputVarType>::value>> + : std::true_type {}; + template static constexpr bool has_custom_constructor = has_from_json_obj::value; - rfl::Result get_field(const std::string& _name, - InputObjectType* _obj) const noexcept { - const auto var = - InputVarType(yyjson_obj_get(_obj->val_, _name.c_str())); + rfl::Result 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 - rfl::Result to_basic_type(InputVarType* _var) const noexcept { + rfl::Result to_basic_type(const InputVarType _var) const noexcept { if constexpr (std::is_same, 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, 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>()) { - if (!yyjson_is_num(_var->val_)) { + if (!yyjson_is_num(_var.val_)) { return rfl::Error("Could not cast to double."); } - return static_cast(yyjson_get_num(_var->val_)); + return static_cast(yyjson_get_num(_var.val_)); } else if constexpr (std::is_integral>()) { - if (!yyjson_is_int(_var->val_)) { + if (!yyjson_is_int(_var.val_)) { return rfl::Error("Could not cast to int."); } - return static_cast(yyjson_get_int(_var->val_)); + return static_cast(yyjson_get_int(_var.val_)); } else { static_assert(rfl::always_false_v, "Unsupported type."); } } - rfl::Result to_array(InputVarType* _var) const noexcept { - if (!yyjson_is_arr(_var->val_)) { + rfl::Result 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 to_map( - InputObjectType* _obj) const noexcept { - std::map m; + template + std::array to_fields_array( + const FunctionType _fct, const InputObjectType _obj) const noexcept { + std::array 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> to_map( + const InputObjectType _obj) const noexcept { + std::vector> 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 to_object(InputVarType* _var) const noexcept { - if (!yyjson_is_obj(_var->val_)) { + rfl::Result 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 to_vec(InputArrayType* _arr) const noexcept { + std::vector to_vec(const InputArrayType _arr) const noexcept { std::vector 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 - rfl::Result use_custom_constructor(InputVarType* _var) const noexcept { + rfl::Result 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()); } diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index 2bc1e83d..f628b5d2 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -13,16 +13,19 @@ #include #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 - OutputVarType from_basic_type(const T _var) const noexcept { + OutputVarType from_basic_type(const T& _var) const noexcept { if constexpr (std::is_same, std::string>()) { return OutputVarType(yyjson_mut_strcpy(doc_, _var.c_str())); } else if constexpr (std::is_same, bool>()) { @@ -61,8 +64,10 @@ struct Writer { } else if constexpr (std::is_floating_point>()) { return OutputVarType( yyjson_mut_real(doc_, static_cast(_var))); - } else { + } else if constexpr (std::is_integral>()) { return OutputVarType(yyjson_mut_int(doc_, static_cast(_var))); + } else { + static_assert(rfl::always_false_v, "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, diff --git a/include/rfl/json/load.hpp b/include/rfl/json/load.hpp new file mode 100644 index 00000000..2f34febf --- /dev/null +++ b/include/rfl/json/load.hpp @@ -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 +Result load(const std::string& _fname) { + return rfl::io::load_string(_fname).and_then(read); +} + +} // namespace json +} // namespace rfl + +#endif diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index 0f5ca6d5..10f67666 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -14,15 +14,20 @@ namespace json { using InputObjectType = typename Reader::InputObjectType; using InputVarType = typename Reader::InputVarType; +/// Parses an object from a JSON var. +template +Result read(const InputVarType& _obj) { + const auto r = Reader(); + return Parser::read(r, _obj); +} + /// Parses an object from JSON using reflection. template Result read(const std::string& _json_str) { using PtrType = std::unique_ptr; 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::read(r, &root); + return read(InputVarType(yyjson_doc_get_root(doc))); } } // namespace json diff --git a/include/rfl/json/save.hpp b/include/rfl/json/save.hpp new file mode 100644 index 00000000..614f3917 --- /dev/null +++ b/include/rfl/json/save.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_JSON_SAVE_HPP_ +#define RFL_JSON_SAVE_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/io/save_string.hpp" +#include "rfl/json/write.hpp" + +namespace rfl { +namespace json { + +template +Result save(const std::string& _fname, const T& _obj) { + return rfl::io::save_string(write(_obj)); +} + +} // namespace json +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/AreReaderAndWriter.hpp b/include/rfl/parsing/AreReaderAndWriter.hpp new file mode 100644 index 00000000..70648a3c --- /dev/null +++ b/include/rfl/parsing/AreReaderAndWriter.hpp @@ -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 +concept AreReaderAndWriter = IsReader && IsWriter; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/CustomParser.hpp b/include/rfl/parsing/CustomParser.hpp index bbe3424e..6c26fc20 100644 --- a/include/rfl/parsing/CustomParser.hpp +++ b/include/rfl/parsing/CustomParser.hpp @@ -15,7 +15,7 @@ template struct CustomParser { static Result read(const ReaderType& _r, - auto* _var) noexcept { + const auto& _var) noexcept { const auto to_class = [](auto&& _h) -> Result { try { if constexpr (internal::has_to_class_method_v) { diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp new file mode 100644 index 00000000..d3db7adc --- /dev/null +++ b/include/rfl/parsing/IsReader.hpp @@ -0,0 +1,83 @@ +#ifndef RFL_PARSING_ISREADER_HPP_ +#define RFL_PARSING_ISREADER_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace parsing { + +template +concept IsReader = requires(R r, std::string name, + std::function 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>; + + /// Determines whether a variable is empty (the NULL type). + { r.is_empty(var) } -> std::same_as; + + /// Transforms var to a basic type (bool, integral, + /// floating point, std::string) + { r.template to_basic_type(var) } -> std::same_as>; + + /// 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>; + + /// Casts var as an InputArrayType. + { + r.to_array(var) + } -> std::same_as>; + + /// Iterates through an object and writes the contained key-value pairs into + /// a vector. + { + r.to_map(obj) + } -> std::same_as< + std::vector>>; + + /// Casts var as an InputObjectType. + { + r.to_object(var) + } -> std::same_as>; + + /// Iterates through an array and writes the contained vars into + /// a vector. + { r.to_vec(arr) } -> std::same_as>; + + /// Uses the custom constructor, if it has been determined that T has one + /// (see above). + { + r.template use_custom_constructor(var) + } -> std::same_as>; +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/IsWriter.hpp b/include/rfl/parsing/IsWriter.hpp new file mode 100644 index 00000000..351f114f --- /dev/null +++ b/include/rfl/parsing/IsWriter.hpp @@ -0,0 +1,50 @@ +#ifndef RFL_PARSING_ISWRITER_HPP_ +#define RFL_PARSING_ISWRITER_HPP_ + +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace parsing { + +template +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; + + /// Returns an empty var (usually the NULL type). + { w.empty_var() } -> std::same_as; + + /// Generates a var from a basic type (std::string, bool, floating point or + /// integral). + { w.from_basic_type(t) } -> std::same_as; + + /// Generates a new, empty array. + { w.new_array() } -> std::same_as; + + /// Generates a new, empty object. + { w.new_object() } -> std::same_as; + + /// Determines whether the var is empty (the NULL type). + { w.is_empty(var) } -> std::same_as; + + /// Adds a new field to obj, thus mutating it. + { w.set_field(name, var, &obj) } -> std::same_as; +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index fda9f122..d6395ab0 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -11,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -34,7 +36,11 @@ #include "rfl/internal/no_duplicate_field_names.hpp" #include "rfl/internal/to_ptr_named_tuple.hpp" #include "rfl/named_tuple_t.hpp" +#include "rfl/parsing/AreReaderAndWriter.hpp" +#include "rfl/parsing/is_forward_list.hpp" +#include "rfl/parsing/is_map_like.hpp" #include "rfl/parsing/is_required.hpp" +#include "rfl/parsing/is_set_like.hpp" #include "rfl/to_named_tuple.hpp" namespace rfl { @@ -42,20 +48,22 @@ namespace parsing { // ---------------------------------------------------------------------------- -template +template +requires AreReaderAndWriter struct Parser; // ---------------------------------------------------------------------------- /// Default case - anything that cannot be explicitly matched. -template +template +requires AreReaderAndWriter struct Parser { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const ReaderType& _r, InputVarType* _var) noexcept { - if constexpr (ReaderType::template has_custom_constructor) { + static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (R::template has_custom_constructor) { return _r.template use_custom_constructor(_var); } else { if constexpr (internal::has_reflection_type_v) { @@ -67,9 +75,8 @@ struct Parser { return Error(e.what()); } }; - return Parser::read( - _r, _var) - .and_then(wrap_in_t); + return Parser::read(_r, _var).and_then( + wrap_in_t); } else if constexpr (std::is_class_v && !std::is_same()) { using NamedTupleType = named_tuple_t; @@ -80,9 +87,8 @@ struct Parser { return Error(e.what()); } }; - return Parser::read( - _r, _var) - .and_then(to_struct); + return Parser::read(_r, _var).and_then( + to_struct); } else { return _r.template to_basic_type>(_var); } @@ -90,36 +96,35 @@ struct Parser { } /// Converts the variable to a JSON type. - static auto write(const WriterType& _w, const T& _var) noexcept { + static auto write(const W& _w, const T& _var) noexcept { if constexpr (internal::has_reflection_type_v) { using ReflectionType = std::decay_t; if constexpr (internal::has_reflection_method_v) { - return Parser::write( - _w, _var.reflection()); + return Parser::write(_w, + _var.reflection()); } else { const auto& [r] = _var; - return Parser::write(_w, - r); + return Parser::write(_w, r); } } else if constexpr (std::is_class_v && !std::is_same()) { const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var); using PtrNamedTupleType = std::decay_t; - return Parser::write( - _w, ptr_named_tuple); + return Parser::write(_w, ptr_named_tuple); } else { return _w.from_basic_type(_var); } } }; -template -struct Parser { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter +struct Parser { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const ReaderType& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, const InputVarType& _var) noexcept { static_assert( always_false_v, "Reading into raw pointers is dangerous and therefore unsupported. " @@ -129,29 +134,29 @@ struct Parser { } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, const T* _ptr) noexcept { + static OutputVarType write(const W& _w, const T* _ptr) noexcept { if (!_ptr) { return _w.empty_var(); } - return Parser>::write(_w, - *_ptr); + return Parser>::write(_w, *_ptr); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_vec = [&](const auto& _arr) { return _r.to_vec(_arr); }; const auto check_size = [](auto _vec) -> Result> { @@ -173,13 +178,11 @@ struct Parser> { .and_then(extract); } - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::array& _arr) noexcept { auto arr = _w.new_array(); for (auto it = _arr.begin(); it != _arr.end(); ++it) { - _w.add( - Parser>::write(_w, *it), - &arr); + _w.add(Parser>::write(_w, *it), &arr); } return OutputVarType(arr); } @@ -188,7 +191,7 @@ struct Parser> { /// Extracts values from the array, field by field. template static Result> extract_field_by_field( - const ReaderType& _r, std::vector _vec, + const R& _r, std::vector _vec, AlreadyExtracted&&... _already_extracted) noexcept { constexpr size_t i = sizeof...(AlreadyExtracted); if constexpr (i == _size) { @@ -199,54 +202,51 @@ struct Parser> { std::move(_already_extracted)..., std::move(new_entry)); }; - return extract_single_field(_r, &_vec).and_then(extract_next); + return extract_single_field(_r, _vec).and_then(extract_next); } } /// Extracts a single field from a JSON. template - static auto extract_single_field(const ReaderType& _r, - std::vector* _vec) noexcept { - return Parser::read(_r, &((*_vec)[_i])); + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + return Parser::read(_r, _vec[_i]); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - const auto to_box = [&](auto&& _t) { + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_box); + return Parser>::read(_r, _var).transform(to_box); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, - const Box& _box) noexcept { - return Parser>::write(_w, - *_box); + static OutputVarType write(const W& _w, const Box& _box) noexcept { + return Parser>::write(_w, *_box); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result> read(const R& _r, + const InputVarType& _var) noexcept { const auto to_type = [](const auto& _str) { return Literal<_fields...>::from_string(_str); }; @@ -261,7 +261,7 @@ struct Parser> { } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const Literal<_fields...>& _literal) noexcept { return _w.from_basic_type(_literal.name()); } @@ -269,82 +269,103 @@ struct Parser> { // ---------------------------------------------------------------------------- -template -struct Parser> { +/// Used for maps for which the key type is std::string. These are represented +/// as objects. +template +requires AreReaderAndWriter +struct MapParser { public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as a std::map. - static Result> read( - const ReaderType& _r, InputVarType* _var) noexcept { - const auto get_pair = [&](auto _pair) { - const auto to_pair = [&](const ValueType& _val) { - return std::make_pair(_pair.first, _val); + using ValueType = std::decay_t; + + static Result read(const R& _r, + const InputVarType& _var) noexcept { + const auto get_pair = [&](auto& _pair) { + const auto to_pair = [&](ValueType&& _val) { + return std::make_pair(std::move(_pair.first), std::move(_val)); }; - return Parser>::read(_r, &_pair.second) + return Parser>::read(_r, _pair.second) .transform(to_pair) .value(); }; - const auto to_map = [&_r, get_pair](auto _obj) { - using namespace std::ranges::views; - auto m = _r.to_map(&_obj); - auto range = m | transform(get_pair); + const auto to_map = [&_r, + get_pair](const auto& _obj) -> Result { + auto m = _r.to_map(_obj); + MapType res; try { - return std::map(range.begin(), - range.end()); + for (auto& p : m) { + res.insert(get_pair(p)); + } } catch (std::exception& e) { return Error(e.what()); } + return res; }; return _r.to_object(_var).and_then(to_map); } - /// Transform a std::map into an object - static OutputVarType write( - const WriterType& _w, - const std::map& _m) noexcept { + static OutputVarType write(const W& _w, const MapType& _m) noexcept { auto obj = _w.new_object(); for (const auto& [k, v] : _m) { - _w.set_field( - k, - Parser>::write( - _w, v), - &obj); + _w.set_field(k, Parser>::write(_w, v), + &obj); } return obj; } }; +template +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; + // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; public: /// Generates a NamedTuple from a JSON Object. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; - const auto build = [&](auto _map) { - return build_named_tuple_recursively(_r, _map); + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto& indices = field_indices(); + const auto fct = [&](const std::string_view& _str) -> std::int16_t { + const auto it = indices.find(_str); + return it != indices.end() ? it->second + : static_cast(-1); }; - return _r.to_object(_var).transform(to_map).and_then(build); + const auto to_fields_array = [&](auto _obj) { + return _r.template to_fields_array(fct, + _obj); + }; + const auto build = [&](auto _fields_vec) { + return build_named_tuple_recursively(_r, _fields_vec); + }; + return _r.to_object(_var).transform(to_fields_array).and_then(build); } /// Transforms a NamedTuple into a JSON object. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const NamedTuple& _tup) noexcept { auto obj = _w.new_object(); build_object_recursively(_w, _tup, &obj); @@ -355,44 +376,104 @@ struct Parser> { /// Builds the named tuple field by field. template static Result> build_named_tuple_recursively( - const ReaderType& _r, const std::map& _map, + const R& _r, + const std::array& _fields_vec, Args&&... _args) noexcept { - const auto size = sizeof...(Args); + constexpr auto i = sizeof...(Args); - if constexpr (size == sizeof...(FieldTypes)) { + if constexpr (i == sizeof...(FieldTypes)) { return NamedTuple(std::move(_args)...); } else { using FieldType = typename std::tuple_element< - size, typename NamedTuple::Fields>::type; + i, typename NamedTuple::Fields>::type; using ValueType = std::decay_t; - const auto key = FieldType::name_.str(); + const auto& f = std::get(_fields_vec); - const auto it = _map.find(key); - - if (it == _map.end()) { + if (_r.is_empty(f)) { if constexpr (is_required()) { - return Error("Field named '" + key + "' not found!"); + const auto key = FieldType::name_.str(); + return collect_errors( + _r, _fields_vec, + std::vector( + {Error("Field named '" + key + "' not found!")})); } else { return build_named_tuple_recursively( - _r, _map, std::move(_args)..., FieldType(ValueType())); + _r, _fields_vec, std::move(_args)..., + FieldType(ValueType())); } } const auto build = [&](auto&& _value) { return build_named_tuple_recursively( - _r, _map, std::move(_args)..., + _r, _fields_vec, std::move(_args)..., FieldType(std::move(_value))); }; - return get_value(_r, *it).and_then(build); + const auto handle_error = [&](Error&& _error) { + return collect_errors( + _r, _fields_vec, std::vector({std::move(_error)})); + }; + + return get_value(_r, f) + .or_else(handle_error) + .and_then(build); + } + } + + /// If something went wrong, we want to collect all of the errors - it's + /// just good UX. + template + static Error collect_errors( + const R& _r, + const std::array& _fields_vec, + std::vector _errors) noexcept { + if constexpr (_i == sizeof...(FieldTypes)) { + if (_errors.size() == 1) { + return std::move(_errors[0]); + } else { + std::string msg = + "Found " + std::to_string(_errors.size()) + " errors:"; + for (size_t i = 0; i < _errors.size(); ++i) { + msg += "\n" + std::to_string(i + 1) + ") " + + _errors.at(i).what(); + } + return Error(msg); + } + } else { + using FieldType = typename std::tuple_element< + _i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get<_i>(_fields_vec); + + if (_r.is_empty(f)) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + _errors.emplace_back( + Error("Field named '" + key + "' not found.")); + } + return collect_errors<_i + 1>(_r, _fields_vec, + std::move(_errors)); + } + + const auto add_error_if_applicable = + [&](Error&& _error) -> Result { + _errors.emplace_back(std::move(_error)); + return _error; + }; + + get_value(_r, f).or_else(add_error_if_applicable); + + return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors)); } } /// Builds the object field by field. template - static void build_object_recursively(const WriterType& _w, + static void build_object_recursively(const W& _w, const NamedTuple& _tup, OutputObjectType* _ptr) noexcept { if constexpr (_i >= sizeof...(FieldTypes)) { @@ -402,11 +483,10 @@ struct Parser> { typename std::tuple_element<_i, std::tuple>::type; using ValueType = std::decay_t; - auto value = Parser::write( - _w, rfl::get<_i>(_tup)); + auto value = Parser::write(_w, rfl::get<_i>(_tup)); const auto name = FieldType::name_.str(); if constexpr (!is_required()) { - if (!_w.is_empty(&value)) { + if (!_w.is_empty(value)) { _w.set_field(name, value, _ptr); } } else { @@ -416,150 +496,179 @@ struct Parser> { } } - /// Retrieves the value from the object. This is mainly needed to generate a - /// better error message. - template - static auto get_value(const ReaderType& _r, - std::pair _pair) noexcept { - const auto embellish_error = [&](const Error& _e) { - return Error("Failed to parse field '" + _pair.first + - "': " + _e.what()); - }; - return Parser::read(_r, - &_pair.second) - .or_else(embellish_error); + /// Uses a memoization pattern to retrieve the field indices. + /// There are some objects that we are likely to parse many times, + /// so we only calculate these indices once. + static const auto& field_indices() noexcept { + if (field_indices_.size() == 0) { + set_field_indices(); + } + return Parser>::field_indices_; } + + /// Retrieves the value from the object. This is mainly needed to + /// generate a better error message. + template + static auto get_value(const R& _r, const InputVarType _var) noexcept { + const auto embellish_error = [&](const Error& _e) { + const auto key = FieldType::name_.str(); + return Error("Failed to parse field '" + key + "': " + _e.what()); + }; + using ValueType = std::decay_t; + return Parser::read(_r, _var).or_else(embellish_error); + } + + /// Builds the object field by field. + template + static void set_field_indices() noexcept { + if constexpr (_i >= sizeof...(FieldTypes)) { + return; + } else { + using FieldType = + typename std::tuple_element<_i, + std::tuple>::type; + const auto name = FieldType::name_.string_view(); + Parser>::field_indices_[name] = + static_cast(_i); + set_field_indices<_i + 1>(); + } + } + + private: + /// Maps each of the field names to an index signifying their order. + static inline std::unordered_map + field_indices_; }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result> read(const R& _r, + const InputVarType& _var) noexcept { if (_r.is_empty(_var)) { return std::optional(); } - const auto to_opt = [&_r](auto&& _t) { - return std::make_optional(_t); - }; - return Parser>::read(_r, _var) - .transform(to_opt); + const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; + return Parser>::read(_r, _var).transform(to_opt); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::optional& _o) noexcept { if (!_o) { return _w.empty_var(); } - return Parser>::write(_w, *_o); + return Parser>::write(_w, *_o); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - const auto to_ref = [&](auto&& _t) { return Ref::make(_t); }; - return Parser>::read(_r, _var) - .transform(to_ref); + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_ref = [&](auto&& _t) { + return Ref::make(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ref); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, - const Ref& _ref) noexcept { - return Parser>::write(_w, - *_ref); + static OutputVarType write(const W& _w, const Ref& _ref) noexcept { + return Parser>::write(_w, *_ref); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - if (_r.is_empty(_var)) { + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(*_var)) { return std::shared_ptr(); } - const auto to_ptr = [](auto&& _t) { return std::make_shared(_t); }; - return Parser>::read(_r, _var) - .transform(to_ptr); + const auto to_ptr = [](auto&& _t) { + return std::make_shared(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ptr); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::shared_ptr& _s) noexcept { if (!_s) { return _w.empty_var(); } - return Parser>::write(_w, *_s); + return Parser>::write(_w, *_s); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. static Result> read( - const ReaderType& _r, InputVarType* _var) noexcept { + const R& _r, const InputVarType& _var) noexcept { const auto to_pair = [&](auto&& _t) { return std::make_pair(std::move(std::get<0>(_t)), std::move(std::get<1>(_t))); }; - return Parser>::read(_r, _var) + return Parser>::read(_r, _var) .transform(to_pair); } /// Transform a std::pair into an array static OutputVarType write( - const WriterType& _w, - const std::pair& _p) noexcept { - const auto tup = std::make_tuple(_p.first, _p.second); - return Parser>::write(_w, tup); + const W& _w, const std::pair& _p) noexcept { + const auto tup = std::make_tuple(&_p.first, &_p.second); + return Parser< + R, W, std::tuple>::write(_w, + tup); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { using ResultType = Result>; public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const ReaderType& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, const InputVarType& _var) noexcept { const auto get_disc = [&_r](auto _obj) { - return get_discriminator(_r, &_obj); + return get_discriminator(_r, _obj); }; const auto to_result = [&_r, _var](const std::string& _disc_value) { @@ -571,21 +680,19 @@ struct Parser& - _tagged_union) noexcept { + const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& + _tagged_union) noexcept { using VariantType = typename TaggedUnion<_discriminator, AlternativeTypes...>::VariantType; - return Parser::write( - _w, _tagged_union.variant_); + return Parser::write(_w, _tagged_union.variant_); } private: template - static ResultType find_matching_alternative(const ReaderType& _r, - const std::string& _disc_value, - InputVarType* _var) noexcept { + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { if constexpr (_i == sizeof...(AlternativeTypes)) { return Error("Could not parse tagged union, could not match " + _discriminator.str() + " '" + _disc_value + "'."); @@ -601,13 +708,13 @@ struct Parser::read( - _r, _var) + return Parser::read(_r, _var) .transform(to_tagged_union) .or_else(embellish_error); @@ -619,7 +726,7 @@ struct Parser get_discriminator( - const ReaderType& _r, InputObjectType* _obj) noexcept { + const R& _r, const InputObjectType& _obj) noexcept { const auto embellish_error = [](const auto& _err) { return Error( "Could not parse tagged union: Could not find field '" + @@ -627,7 +734,7 @@ struct Parser(&_var); + return _r.template to_basic_type(_var); }; return _r.get_field(_discriminator.str(), _obj) @@ -653,18 +760,19 @@ struct Parser -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { - const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_vec = [&](auto _arr) { return _r.to_vec(_arr); }; const auto check_size = [](auto _vec) -> Result> { @@ -686,7 +794,7 @@ struct Parser> { .and_then(extract); } - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::tuple& _tup) noexcept { auto arr = _w.new_array(); to_array<0>(_w, _tup, &arr); @@ -697,42 +805,41 @@ struct Parser> { /// Extracts values from the array, field by field. template static Result> extract_field_by_field( - const ReaderType& _r, std::vector _vec, + const R& _r, std::vector _vec, AlreadyExtracted&&... _already_extracted) noexcept { constexpr size_t i = sizeof...(AlreadyExtracted); if constexpr (i == sizeof...(Ts)) { - return std::tuple(std::make_tuple(_already_extracted...)); + return std::tuple( + std::make_tuple(std::move(_already_extracted)...)); } else { const auto extract_next = [&](auto&& new_entry) { return extract_field_by_field(_r, std::move(_vec), std::move(_already_extracted)..., std::move(new_entry)); }; - return extract_single_field(_r, &_vec).and_then(extract_next); + return extract_single_field(_r, _vec).and_then(extract_next); } } /// Extracts a single field from a JSON. template - static auto extract_single_field(const ReaderType& _r, - std::vector* _vec) noexcept { + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { using NewFieldType = std::decay_t< typename std::tuple_element<_i, std::tuple>::type>; - return Parser::read( - _r, &((*_vec)[_i])); + return Parser::read(_r, _vec[_i]); } /// Transforms a tuple to an array. template - static void to_array(const WriterType& _w, const std::tuple& _tup, + static void to_array(const W& _w, const std::tuple& _tup, OutputArrayType* _ptr) noexcept { if constexpr (_i < sizeof...(Ts)) { using NewFieldType = std::decay_t< typename std::tuple_element<_i, std::tuple>::type>; const auto val = - Parser::write( - _w, std::get<_i>(_tup)); + Parser::write(_w, std::get<_i>(_tup)); _w.add(val, _ptr); to_array<_i + 1>(_w, _tup, _ptr); } @@ -741,31 +848,31 @@ struct Parser> { // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result> read(const R& _r, + const InputVarType& _var) noexcept { if (_r.is_empty(_var)) { return std::unique_ptr(); } const auto to_ptr = [](auto&& _t) { return std::make_unique(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_ptr); + return Parser>::read(_r, _var).transform(to_ptr); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::unique_ptr& _s) noexcept { if (!_s) { return _w.empty_var(); } - return Parser>::write(_w, *_s); + return Parser>::write(_w, *_s); } }; @@ -773,24 +880,26 @@ struct Parser> { /// To be used when all options of the variants are rfl::Field. Essentially, /// this is an externally tagged union. -template +template +requires AreReaderAndWriter> struct FieldVariantParser { using ResultType = Result>; public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const ReaderType& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, const InputVarType& _var) noexcept { static_assert( internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); - const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; + const auto to_map = [&](auto _obj) { return _r.to_map(_obj); }; const auto to_result = [&](auto _map) -> ResultType { if (_map.size() != 1) { @@ -801,26 +910,26 @@ struct FieldVariantParser { } const auto it = _map.begin(); const auto& disc_value = it->first; - auto& var = it->second; - return find_matching_alternative(_r, disc_value, &var); + const auto& var = it->second; + return find_matching_alternative(_r, disc_value, var); }; return _r.to_object(_var).transform(to_map).and_then(to_result); } /// Expresses the variables as a JSON type. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::variant& _v) noexcept { static_assert( internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); const auto handle = [&](const auto& _field) { const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); using NamedTupleType = std::decay_t; - return Parser::write( - _w, named_tuple); + return Parser::write(_w, named_tuple); }; return std::visit(handle, _v); @@ -828,12 +937,13 @@ struct FieldVariantParser { private: template - static ResultType find_matching_alternative(const ReaderType& _r, - const std::string& _disc_value, - InputVarType* _var) noexcept { + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { return Error( - "Could not parse std::variant, could not match field named '" + + "Could not parse std::variant, could not match field named " + "'" + _disc_value + "'."); } else { using FieldType = std::decay_t::read(_r, _var) + return Parser::read(_r, _var) .transform(to_variant) .or_else(embellish_error); } else { @@ -866,20 +976,20 @@ struct FieldVariantParser { // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. template static Result> read( - const ReaderType& _r, InputVarType* _var, + const R& _r, const InputVarType& _var, const std::string _errors = "") noexcept { if constexpr (_i == 0 && internal::all_fields>()) { - return FieldVariantParser::read(_r, _var); + return FieldVariantParser::read(_r, _var); } else if constexpr (_i == sizeof...(FieldTypes)) { return Error("Could not parse variant: " + _errors); } else { @@ -889,14 +999,15 @@ struct Parser> { const auto try_next = [&_r, _var, &_errors](const auto& _err) { auto errors = _errors; - errors += std::string("\n -") + _err.what(); + errors += std::string("\n " + std::to_string(_i + 1) + ")") + + _err.what(); return read<_i + 1>(_r, _var, errors); }; using AltType = std::decay_t< std::variant_alternative_t<_i, std::variant>>; - return Parser::read(_r, _var) + return Parser::read(_r, _var) .transform(to_variant) .or_else(try_next); } @@ -904,15 +1015,13 @@ struct Parser> { /// Expresses the variables as a JSON type. static OutputVarType write( - const WriterType& _w, - const std::variant& _variant) noexcept { + const W& _w, const std::variant& _variant) noexcept { if constexpr (internal::all_fields>()) { - return FieldVariantParser::write(_w, _variant); + return FieldVariantParser::write(_w, _variant); } else { const auto handle = [&](const auto& _v) { using Type = std::decay_t; - return Parser::write(_w, _v); + return Parser::write(_w, _v); }; return std::visit(handle, _variant); } @@ -922,84 +1031,152 @@ struct Parser> { // ---------------------------------------------------------------------------- /// This can be used for data structures that would be expressed as array in -/// serialized format (std::vector, std::set, std::deque, ...). -template +/// serialized format (std::vector, std::set, std::deque, ...), +/// but also includes map-like types, when the key is not of type +/// std::string. +template +requires AreReaderAndWriter struct VectorParser { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; using T = typename VecType::value_type; - static Result read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result read(const R& _r, + const InputVarType& _var) noexcept { using namespace std::ranges::views; - const auto get_result = [&](auto& _v) { - return std::move( - Parser>::read(_r, &_v) - .value()); + const auto get_elem = [&](auto& _v) { + return Parser>::read(_r, _v).value(); }; - const auto to_vec = [&](InputArrayType _arr) -> Result { - auto input_vars = _r.to_vec(&_arr); - auto range = input_vars | transform(get_result); + const auto get_pair = [&](auto& _v) { + if constexpr (is_map_like()) { + using K = std::decay_t; + using V = std::decay_t; + return Parser>>::read(_r, _v) + .value(); + } + }; + + const auto to_container = + [&](InputArrayType&& _arr) -> Result { + auto input_vars = _r.to_vec(_arr); + VecType vec; + if constexpr (is_forward_list()) { + for (auto it = input_vars.rbegin(); it != input_vars.rend(); + ++it) { + vec.emplace_front(get_elem(*it)); + } + } else if constexpr (is_map_like()) { + for (auto& v : input_vars) { + vec.insert(get_pair(v)); + } + } else if constexpr (is_set_like()) { + for (auto& v : input_vars) { + vec.insert(get_elem(v)); + } + } else { + for (auto& v : input_vars) { + vec.emplace_back(get_elem(v)); + } + } + return vec; + }; + + const auto to_result = [&](InputArrayType&& _arr) -> Result { try { - return Result(VecType(range.begin(), range.end())); + return Result( + to_container(std::forward(_arr))); } catch (std::exception& e) { return Error(e.what()); } }; - return _r.to_array(_var).and_then(to_vec); + return _r.to_array(_var).and_then(to_result); } - static OutputVarType write(const WriterType& _w, - const VecType& _vec) noexcept { + static OutputVarType write(const W& _w, const VecType& _vec) noexcept { auto arr = _w.new_array(); - for (auto it = _vec.begin(); it != _vec.end(); ++it) { - _w.add( - Parser>::write(_w, *it), - &arr); + for (const auto& v : _vec) { + _w.add(Parser>::write(_w, v), &arr); } return OutputVarType(arr); } }; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/is_forward_list.hpp b/include/rfl/parsing/is_forward_list.hpp new file mode 100644 index 00000000..2ac6fe79 --- /dev/null +++ b/include/rfl/parsing/is_forward_list.hpp @@ -0,0 +1,22 @@ +#ifndef RFL_PARSING_IS_FORWARD_LIST_HPP_ +#define RFL_PARSING_IS_FORWARD_LIST_HPP_ + +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_forward_list; + +template +class is_forward_list : public std::false_type {}; + +template +class is_forward_list> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/is_map_like.hpp b/include/rfl/parsing/is_map_like.hpp new file mode 100644 index 00000000..34249982 --- /dev/null +++ b/include/rfl/parsing/is_map_like.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_IS_MAP_LIKE_HPP_ +#define RFL_PARSING_IS_MAP_LIKE_HPP_ + +#include +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_map_like; + +template +class is_map_like : public std::false_type {}; + +template +class is_map_like> : public std::true_type {}; + +template +class is_map_like> : public std::true_type {}; + +template +class is_map_like> : public std::true_type {}; + +template +class is_map_like> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/is_set_like.hpp b/include/rfl/parsing/is_set_like.hpp new file mode 100644 index 00000000..9801c750 --- /dev/null +++ b/include/rfl/parsing/is_set_like.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_IS_SET_LIKE_HPP_ +#define RFL_PARSING_IS_SET_LIKE_HPP_ + +#include +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_set_like; + +template +class is_set_like : public std::false_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/tests/test_box.hpp b/tests/test_box.hpp index 1ff2730c..9317efdd 100644 --- a/tests/test_box.hpp +++ b/tests/test_box.hpp @@ -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(leaf1), - .greater = rfl::make_box(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_box(DecisionTree{leaf1}), + .greater = rfl::make_box(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; diff --git a/tests/test_custom_constructor.hpp b/tests/test_custom_constructor.hpp new file mode 100644 index 00000000..4ca9c657 --- /dev/null +++ b/tests/test_custom_constructor.hpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +#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 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(std::move(_nt)); + }; + return rfl::json::read>(_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( + 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; + } +} diff --git a/tests/test_deque.hpp b/tests/test_deque.hpp new file mode 100644 index 00000000..78e8fec5 --- /dev/null +++ b/tests/test_deque.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + 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"}]})"); +} diff --git a/tests/test_error_messages.hpp b/tests/test_error_messages.hpp new file mode 100644 index 00000000..139c9dc0 --- /dev/null +++ b/tests/test_error_messages.hpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +#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> children; + }; + + const std::string faulty_string = + R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})"; + + const auto result = rfl::json::read(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; +} diff --git a/tests/test_forward_list.hpp b/tests/test_forward_list.hpp new file mode 100644 index 00000000..8ccfdb21 --- /dev/null +++ b/tests/test_forward_list.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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"}]})"); +} diff --git a/tests/test_list.hpp b/tests/test_list.hpp new file mode 100644 index 00000000..06de7e72 --- /dev/null +++ b/tests/test_list.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + 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"}]})"); +} diff --git a/tests/test_map.hpp b/tests/test_map.hpp new file mode 100644 index 00000000..efb793bf --- /dev/null +++ b/tests/test_map.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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"}]]})"); +} diff --git a/tests/test_multimap.hpp b/tests/test_multimap.hpp new file mode 100644 index 00000000..6746613e --- /dev/null +++ b/tests/test_multimap.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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"}]]})"); +} diff --git a/tests/test_multiset.hpp b/tests/test_multiset.hpp new file mode 100644 index 00000000..21d7062e --- /dev/null +++ b/tests/test_multiset.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::multiset({"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"]})"); +} diff --git a/tests/test_ref.hpp b/tests/test_ref.hpp index 8c353f5d..b7fe3e90 100644 --- a/tests/test_ref.hpp +++ b/tests/test_ref.hpp @@ -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(leaf1), - .greater = rfl::make_ref(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_ref(DecisionTree{leaf1}), + .greater = rfl::make_ref(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; diff --git a/tests/test_set.hpp b/tests/test_set.hpp new file mode 100644 index 00000000..97e3834b --- /dev/null +++ b/tests/test_set.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::set({"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"]})"); +} diff --git a/tests/test_string_map.hpp b/tests/test_string_map.hpp new file mode 100644 index 00000000..b06cabf8 --- /dev/null +++ b/tests/test_string_map.hpp @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_map() { + std::cout << "test_string_map" << std::endl; + + std::map> homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read(homer, R"({"firstName":"Homer","lastName":"Simpson"})"); +} diff --git a/tests/test_string_unordered_map.hpp b/tests/test_string_unordered_map.hpp new file mode 100644 index 00000000..54238ec2 --- /dev/null +++ b/tests/test_string_unordered_map.hpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_unordered_map() { + std::cout << "test_string_unordered_map" << std::endl; + + using Map = std::unordered_map>; + Map homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unique_ptr2.hpp b/tests/test_unique_ptr2.hpp index aae61b15..4fab614c 100644 --- a/tests/test_unique_ptr2.hpp +++ b/tests/test_unique_ptr2.hpp @@ -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(leaf1), - .greater = std::make_unique(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = std::make_unique(DecisionTree{leaf1}), + .greater = std::make_unique(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; diff --git a/tests/test_unordered_map.hpp b/tests/test_unordered_map.hpp new file mode 100644 index 00000000..b91940b1 --- /dev/null +++ b/tests/test_unordered_map.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unordered_multimap.hpp b/tests/test_unordered_multimap.hpp new file mode 100644 index 00000000..757118df --- /dev/null +++ b/tests/test_unordered_multimap.hpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unordered_multiset.hpp b/tests/test_unordered_multiset.hpp new file mode 100644 index 00000000..11591da4 --- /dev/null +++ b/tests/test_unordered_multiset.hpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_multiset({"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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unordered_set.hpp b/tests/test_unordered_set.hpp new file mode 100644 index 00000000..f4602a64 --- /dev/null +++ b/tests/test_unordered_set.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_set({"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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 074de544..b79fd5a5 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -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; }