From de46fa6f24f578c435920a007ca70d1e2652cd0f Mon Sep 17 00:00:00 2001 From: Jeremy Perez Date: Tue, 25 Jun 2024 18:42:45 +0200 Subject: [PATCH] added first draft of docs --- docs/concepts/custom_classes.md | 238 ++++++ docs/concepts/errors.md | 179 ++++ docs/concepts/field_syntax.md | 273 ++++++ docs/concepts/processors.md | 158 ++++ docs/concepts/serialization.md | 260 ++++++ docs/concepts/structs.md | 333 ++++++++ docs/concepts/supported_formats.md | 615 ++++++++++++++ docs/concepts/supported_formats/bson.md | 106 +++ docs/concepts/supported_formats/cbor.md | 100 +++ .../concepts/supported_formats/flexbuffers.md | 246 ++++++ docs/concepts/supported_formats/json.md | 116 +++ .../concepts/supported_formats/json_schema.md | 192 +++++ .../supporting_your_own_format.md | 258 ++++++ docs/concepts/supported_formats/toml.md | 98 +++ docs/concepts/supported_formats/xml.md | 245 ++++++ docs/concepts/supported_formats/yaml.md | 98 +++ docs/concepts/types.md | 804 ++++++++++++++++++ docs/concepts/validators.md | 119 +++ docs/contributing.md | 66 ++ docs/error_messages.md | 21 + docs/errors/result.md | 159 ++++ docs/errors/validation_errors.md | 21 + docs/index.md | 215 +++++ docs/install.md | 68 ++ docs/reflective_programming.md | 98 +++ docs/stylesheets/extra.css | 7 + docs/validation_errors.md | 21 + docs/welcome.md | 0 flake.nix | 46 + 29 files changed, 5160 insertions(+) create mode 100644 docs/concepts/custom_classes.md create mode 100644 docs/concepts/errors.md create mode 100644 docs/concepts/field_syntax.md create mode 100644 docs/concepts/processors.md create mode 100644 docs/concepts/serialization.md create mode 100644 docs/concepts/structs.md create mode 100644 docs/concepts/supported_formats.md create mode 100644 docs/concepts/supported_formats/bson.md create mode 100644 docs/concepts/supported_formats/cbor.md create mode 100644 docs/concepts/supported_formats/flexbuffers.md create mode 100644 docs/concepts/supported_formats/json.md create mode 100644 docs/concepts/supported_formats/json_schema.md create mode 100644 docs/concepts/supported_formats/supporting_your_own_format.md create mode 100644 docs/concepts/supported_formats/toml.md create mode 100644 docs/concepts/supported_formats/xml.md create mode 100644 docs/concepts/supported_formats/yaml.md create mode 100644 docs/concepts/types.md create mode 100644 docs/concepts/validators.md create mode 100644 docs/contributing.md create mode 100644 docs/error_messages.md create mode 100644 docs/errors/result.md create mode 100644 docs/errors/validation_errors.md create mode 100644 docs/index.md create mode 100644 docs/install.md create mode 100644 docs/reflective_programming.md create mode 100644 docs/stylesheets/extra.css create mode 100644 docs/validation_errors.md create mode 100644 docs/welcome.md create mode 100644 flake.nix diff --git a/docs/concepts/custom_classes.md b/docs/concepts/custom_classes.md new file mode 100644 index 00000000..a78625dc --- /dev/null +++ b/docs/concepts/custom_classes.md @@ -0,0 +1,238 @@ + +Reflection implies that all your fields are public. But in object-oriented programming, you often don't want +that. If your class is more than a trivial, behaviorless struct, you often want to make your fields private. + +If you want your class to be supported by reflect-cpp, it needs to have the following: + +1. It needs to publicly define a type called `ReflectionType` using `using` or `typedef`. +2. It needs to have a constructor that accepts your `ReflectionType` as an argument. +3. It needs to contain a method called `reflection` that returns said `ReflectionType` (or a reference thereto). + +If you class fulfills these three conditions, then it is fully supported by all serialization and deserialization +routines in reflect-cpp. + +If you absolutely do not want to make any changes to your original class, you can implement a [custom parser](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md). + +## Using an Impl struct + +```cpp +struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; +}; + +class Person { + public: + // 1) Publicly define `ReflectionType` + using ReflectionType = PersonImpl; + + // 2) Constructor that accepts your `ReflectionType` + Person(const PersonImpl& _impl): impl(_impl) {} + + ~Person() = default; + + // 3) Method called `reflection` that returns `ReflectionType` + const ReflectionType& reflection() const { return impl; } + + // ...add some more methods here... + + private: + PersonImpl impl; +}; +``` + +## Matching variables, the safe way + +`rfl::Field` is designed in a way that you have to explicitly initialize +every the field (using `rfl::default_value`, if necessary), otherwise +you will get a compile-time error. + +A frequent error that happens during serialization/deserialization is that programmers +add a field to their class (`Person` in this example), but forget to update +their serialization routine. + +The example as shown below will protect you from any such errors, as all +fields will have to be explicitly initialized, otherwise you will get a +compile-time error. If you add a new field to `Person` you will have to +add it to `PersonImpl` as well and then explicitly initialize it in the +constructor. + +Don't worry `operator()` in `rfl::Field` is inlined. There won't be any +runtime overhead. + +```cpp +struct PersonImpl { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"age", int> age; +}; + +class Person { + public: + // 1) Publicly define `ReflectionType` + using ReflectionType = PersonImpl; + + // 2) Constructor that accepts your `ReflectionType` + // This as the additional benefit that not only the types, + // but also the names of the fields will be checked at compile time. + Person(const PersonImpl& _impl): first_name(_impl.first_name), + last_name(_impl.last_name), age(_impl.age) {} + + ~Person() = default; + + // 3) Method called `reflection` that returns `ReflectionType` + ReflectionType reflection() const { + return PersonImpl{ + .first_name = first_name, + .last_name = last_name, + .age = age}; + } + + // ...add some more methods here... + + private: + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"age", int> age; +}; +``` + +## Matching variables, the unsafe way + +If, for any reason, you absolutely cannot change the fields +of your class, you have to make sure that all classes are properly +initialized or face runtime errors. + +```cpp +struct PersonImpl { + // ... same as in Example 1 or 2 +}; + +class Person { + // 1) Publicly define `ReflectionType` + using ReflectionType = PersonImpl; + + // 2) Constructor that accepts your `ReflectionType` + Person(const PersonImpl& _impl): first_name(_impl.first_name()), + last_name(_impl.last_name()), age(_impl.age()) {} + + // ... same as in Example 2 + + private: + std::string first_name; + std::string last_name; + int age; +}; +``` + +## Custom parsers + +If you absolutely do not want to make any changes to your original classes whatsoever, +you can implement a custom parser using `rfl::parsing::CustomParser`. + +In order to do so, you must do the following: + +You must create a helper struct that *can* be parsed. The helper struct must fulfill the following +conditions: + +1. It must contain a static method called `from_class` that takes your original class as an input and returns the helper struct. This method must not throw an exception. + +2. (Optional) It must contain a method called `to_class` that transforms the helper struct into your original class. This method may throw an exception, if you want to. If you can directly construct your custom class from the field values in the order they were declared in the helper struct, you do not have to write a `to_class` method. + +You can then implement a custom parser for your class like this: + +```cpp +namespace rfl::parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace rfl::parsing +``` + +**Example** + +Suppose your original class looks like this: + +```cpp +struct Person { + Person(const std::string& _first_name, const std::string& _last_name, + const int _age) + : first_name_(_first_name), last_name_(_last_name), age_(_age) {} + + const auto& first_name() const { return first_name_; } + + const auto& last_name() const { return last_name_; } + + auto age() const { return age_; } + + private: + std::string first_name_; + std::string last_name_; + int age_; +}; +``` + +You can then write a helper struct: + +```cpp +struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; + + // 1) Static method that takes your original class as an input and + // returns the helper struct. + // MUST NOT THROW AN EXCEPTION! + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = _p.last_name(), + .age = _p.age()}; + } + + // 2) Const method called `to_class` that transforms the helper struct + // into your original class. + // In this case, the `to_class` method is actually optional, because + // you can directly create Person from the field values. + Person to_class() const { return Person(first_name(), last_name(), age); } +}; +``` + +You then implement the custom parser: + +```cpp +namespace rfl::parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace rfl::parsing +``` + +Now your custom class is fully supported by reflect-cpp. So for instance, you could parse it +inside a vector: + +```cpp +const auto people = rfl::json::read>(json_str).value(); +``` + +As we have noted, in this particular example, the `Person` class can be constructed from the field values in +`PersonImpl` in the exact same order they were declared in `PersonImpl`. So we can drop the `.to_class` method: + +```cpp +struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; + + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = _p.last_name(), + .age = _p.age()}; + } +}; +``` diff --git a/docs/concepts/errors.md b/docs/concepts/errors.md new file mode 100644 index 00000000..03a4702c --- /dev/null +++ b/docs/concepts/errors.md @@ -0,0 +1,179 @@ +## Error messages + +reflect-cpp returns clear and comprehensive error messages: + +```cpp +const std::string faulty_json_string = + R"({"firstName":"Homer","lastName":12345,"town":"Springfield","birthday":"04/19/1987","age":145,"email":"homer(at)simpson.com"})"; +const auto result = rfl::json::read(faulty_json_string); +``` + +Yields the following error message: + +``` +Found 5 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) Failed to parse field 'age': Value expected to be less than or equal to 130, but got 145. +4) Failed to parse field 'email': String 'homer(at)simpson.com' did not match format 'Email': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'. +5) Field named 'children' not found. +``` + +## Result type +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. This is needed for two reasons: + +1. 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. + +2. In some cases, you want to signal to the parser that is fine if some things go wrong. `rfl::Result` is the way to do that. + +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. + +### Using `rfl::Result` for parsing + +Suppose you have a vector with 1000 user-supplied configurations: + +```cpp +const auto configs = rfl::json::read>(json_string); +``` + +Chances are that the user of your software has made as mistake in at least some of these configurations. If you set it up as shown above, `rfl::json::read` will fail if one or more `Config` items contain an error. But sometimes you don't want that. Sometimes you want your software to proceed with the remaining 999 configurations and gently point out to the user that some of the configurations were faulty. + +The solution is to this instead: + +```cpp +const auto configs = rfl::json::read>>(json_string); +``` + +This means `rfl::json::read` is going to cut the end-users of your software some slack. But it also means that you, as the programmer, have to handle the fact that some of the configs might contain errors. + +Below, we will show you how to do that. + +### 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. + +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/concepts/field_syntax.md b/docs/concepts/field_syntax.md new file mode 100644 index 00000000..3afe15f4 --- /dev/null +++ b/docs/concepts/field_syntax.md @@ -0,0 +1,273 @@ +## The `rfl::Field`-syntax + +As we have shown, reflect-cpp can automatically retrieve field names from structs. + +However, it also possible to annotate the fields using `rfl::Field`, 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; +}; +``` + +These annotations are required if you are planning to use a compiler other than MSVC, GCC or clang. + +There are a two things you have to keep in mind: + +!!! tip 1. If you annotate *some* of the fields using `rfl::Field`, then you must annotate *all* of them. + +2. If you are combining structs using `rfl::Flatten`, then they structs combined like this must either be annotated or not. + +You can initilize your struct like this: + +```cpp +const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .children = std::vector()}; +``` + +Note that all fields must be explicitly set. This is on purpose, because it prevents you from accidentally forgetting fields, +which can lead to tricky runtime errors. + +You can initialize a field using `rfl::default_value`: + +```cpp +const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .children = rfl::default_value}; +``` + +You can also initialize fields in the struct declaration itself: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::vector> children = rfl::default_value; +}; +``` + +Because you now have explicitly set those fields, you do not have to do this every time: + +```cpp +const auto bart = Person{.first_name = "Bart"}; + +const auto lisa = Person{.first_name = "Lisa"}; + +const auto maggie = Person{.first_name = "Maggie"}; + +const auto homer = Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + +``` + +You can write this to a JSON string: + +```cpp +const auto json_string = rfl::json::write(homer); +``` + +```json +{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson","children":[]},{"firstName":"Lisa","lastName":"Simpson","children":[]},{"firstName":"Maggie","lastName":"Simpson","children":[]}]} +``` + +And you can parse it back into a struct: + +```cpp +const auto homer = rfl::json::read(json_string).value(); +``` + +## Flatten structs + +In some cases, you want to structs to "inherit" fields from other structs. Unfortunately, doing this +via actual inheritance is not possible at the moment, due to several restrictions imposed by C++. +Instead, we do it via composition, using `rfl::Flatten`. + +Note that you can also have nested flattened fields. If `A` contains `B` and `B` contains `C`, then +all fields will be flattened to a single JSON object. + +If there are duplicate field names, you will get a compile-time error. + +** Example: Every employee is a person ** + +```cpp +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = "Simpson", + .age = 45}, + .employer = "Mr. Burns", + .salary = 60000.0}; + +const auto json_str = rfl::json::write(employee); +``` + +This flattens all fields into a single JSON object: + +```json +{"first_name":"Homer","last_name":"Simpson","age":45,"salary":60000.0} +``` + +** Example, using the `rfl::Field`-syntax.** + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"age", int> age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Field<"salary", float> salary; +}; + +const auto employee = Employee{ + .person = Person{.first_name = "Homer", .last_name = "Simpson", .age = 45}, + .salary = 60000.0 +}; + +const auto json_str = rfl::json::write(employee); +``` + +This flattens all fields into a single JSON object: + +```json +{"firstName":"Homer","lastName":"Simpson","age":45,"salary":60000.0} +``` + + +## Anonymous fields + +If you do not want to serialize field names, you do not have to use `rfl::Field`. You can just write your struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + std::vector children; +}; +``` + +This is referred to as anonymous fields. It is particularly relevant if you are using a binary format. + +This can be fully serialized and deserialized using `rfl::json::read` and `rfl::json::write`. No further annotations are needed. + +However, there are a two things you have to keep in mind: + +1) If you annotate *some* of the fields using either `rfl::Field`, then you must annotate *all* of them using one of these two. +2) If you are combining structs using `rfl::Flatten`, then they structs combined like this must either be annotated or not. + +### Struct flattening with anonymous fields + +Struct flattening also works with anonymous fields: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = "Simpson", + .age = 45}, + .employer = "Mr. Burns", + .salary = 60000.0}; +``` + +This will result in the following JSON: + +```json +["Homer","Simpson",45,"Mr. Burns",60000.0] +``` + +You can even include `std::tuple` (but `std::tuple` itself cannot contain `rfl::Flatten`): + +```cpp +using Person = std::tuple; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = Person{"Homer", "Simpson", 45}, + .employer = "Mr. Burns", + .salary = 60000.0}; +``` + +This will result in the same JSON: + +```json +["Homer","Simpson",45,"Mr. Burns",60000.0] +``` + +## Optional fields + +Usually, when you set up a struct, all of the fields are required. For instance, in the previous example, +we generated a JSON string like this: + +```json +{"firstName":"Bart","lastName":"Simpson","children":[]} +``` + +Likewise, if we read the JSON string and the field "children" is missing, that will result in a runtime error. + +But Bart doesn't have any children. After all, he's only 10 years old. To indicate to the library that the field "children" is optional, +we can use either `std::optional`, `std::shared_ptr` or `std::unique_ptr`. + +If `std::optional` is `std::nullopt` or any of the smart pointers is a `nullptr`, +then the field will not be written to the JSON string. Likewise, when you read the JSON string, the fields will not be required. If you +want the fields to be required, you can use the `rfl::NoOptionals` processor, please refer to the section on processors. + +So this is how we could rewrite the previous example: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + + // Indicates to the library that the field is optional. + std::optional> children; +}; + +const auto bart = Person{.first_name = "Bart"}; + +const auto lisa = Person{.first_name = "Lisa"}; + +const auto maggie = Person{.first_name = "Maggie"}; + +const auto homer = Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + +const auto json_string = rfl::json::write(homer); +``` + +Now, the field "children" is missing for Bart, Lisa and Maggie: + +```json +{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]} +``` diff --git a/docs/concepts/processors.md b/docs/concepts/processors.md new file mode 100644 index 00000000..28650e6d --- /dev/null +++ b/docs/concepts/processors.md @@ -0,0 +1,158 @@ +# Processors + +Processors can be used to apply transformations to struct serialization and deserialization. + +For instance, C++ [usually](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rl-camel) uses `snake_case`, but JSON uses `camelCase`. One way to handle this is `rfl::Rename`, but a more automated way would be to use a *processor*: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + std::vector children; +}; + +const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .age = 45}; + +const auto json_string = + rfl::json::write(homer); + +const auto homer2 = + rfl::json::read(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"firstName":"Homer","lastName":"Simpson","age":45} +``` + +## Supported processors + +reflect-cpp currently supports the following processors: + +- `rfl::AddStructName` +- `rfl::NoOptionals` +- `rfl::SnakeCaseToCamelCase` +- `rfl::SnakeCaseToPascalCase` + +### `rfl::AddStructName` + +It is also possible to add the struct name as an addtional field, like this: + +```cpp +const auto json_string = + rfl::json::write>(homer); + +const auto homer2 = + rfl::json::read>(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"type":"Person","first_name":"Homer","last_name":"Simpson","age":45} +``` + +### `rfl::NoOptionals` + +As we have seen in the section on optional fields, when a `std::optional` is +`std::nullopt`, it is usually not written at all. But if you want them to be explicitly +written as `null`, you can use this processor. The same thing applies to `std::shared_ptr` and +`std::unique_ptr`. + +```cpp +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::optional town = std::nullopt; +}; + +const auto homer = Person{.first_name = "Homer"}; + +rfl::json::write(homer); +``` + +The resulting JSON string looks like this: + +```json +{"first_name":"Homer","last_name":"Simpson","town":null} +``` + +By default, `rfl::json::read` will accept both `"town":null` and just +leaving out the field `town`. However, if you want to require the field +`town` to be included, you can add `rfl::NoOptionals` to `read`: + +``` +rfl::json::read(json_string); +``` + +### `rfl::SnakeCaseToCamelCase` + +Please refer to the example above. + +### `rfl::SnakeCaseToPascalCase` + +If you want `PascalCase` instead of `camelCase`, you can use the appropriate processor: + +```cpp +const auto json_string = + rfl::json::write(homer); + +const auto homer2 = + rfl::json::read(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"FirstName":"Homer","LastName":"Simpson","Age":45} +``` + +## Combining several processors + +You can combine several processors: + +```cpp +const auto json_string = + rfl::json::write>(homer); + +const auto homer2 = + rfl::json::read>(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} +``` + +When you have several processors, it is probably more convenient to combine them like this: + +```cpp +using Processors = rfl::Processors< + rfl::SnakeCaseToCamelCase, rfl::AddStructName<"type">>; + +const auto json_string = rfl::json::write(homer); + +const auto homer2 = rfl::json::read(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} +``` + +## Writing your own processors + +In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter. + +```cpp +struct MyOwnProcessor { + template + static auto process(auto&& _named_tuple) {...} +}; +``` diff --git a/docs/concepts/serialization.md b/docs/concepts/serialization.md new file mode 100644 index 00000000..8df67cbb --- /dev/null +++ b/docs/concepts/serialization.md @@ -0,0 +1,260 @@ +## 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 = ...; + + /// Sets an empty array as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `_size`. Returns the new array for further modification. + OutputArrayType array_as_root(const size_t _size) const noexcept; + + /// Sets an empty object as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `_size`. + /// Returns the new object for further modification. + OutputObjectType object_as_root(const size_t _size) const noexcept; + + /// Sets a null as the root element of the document. Returns OutputVarType + /// containing the null value. + OutputVarType null_as_root() const noexcept; + + /// Sets a basic value (bool, numeric, string) as the root element of the + /// document. Returns an OutputVarType containing the new value. + template + OutputVarType value_as_root(const T& _var) const noexcept; + + /// Adds an empty array to an existing array. Returns the new + /// array for further modification. + OutputArrayType add_array_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + /// Adds an empty array to an existing object. The key or name of the field is + /// signified by `_name`. Returns the new array for further modification. + OutputArrayType add_array_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + /// Adds an empty object to an existing array. Returns the new + /// object for further modification. + OutputObjectType add_object_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept; + + /// Adds an empty object to an existing object. The key or name of the field + /// is signified by `_name`. Returns the new object for further modification. + OutputObjectType add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an array. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_array(const T& _var, + OutputArrayType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an existing object. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_object(const std::string_view& _name, const T& _var, + OutputObjectType* _parent) const noexcept; + + /// Adds a null value to an array. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept; + + /// Adds a null value to an existing object. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + /// Signifies to the writer that we do not want to add any further elements to + /// this array. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + void end_array(OutputArrayType* _arr) const noexcept; + + /// Signifies to the writer that we do not want to add any further elements to + /// this object. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + void end_object(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 {...} + + /// 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 inserts the values into the array + /// reader. See below for a more detailed explanation. + template + std::optional read_array(const ArrayReader& _array_reader, + const InputArrayType& _arr) const noexcept {...} + + /// Iterates through an object and inserts the key-value pairs into the object + /// reader. See below for a more detailed explanation. + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) 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, `read_array` and `read_object` probably require further explanation. + +### `read_array` + +`read_array` expects an `ArrayReader` class which might come in several forms. But all +of these forms have a method with the following signature: + +```cpp +std::optional read(const InputVarType& _var) const noexcept; +``` + +Within your implementation of `read_array`, you must iterate through the array passed +to the function and then insert the resulting values into `array_reader.read`. If +`array_reader.read` returns an error, then you must return that error immediately. + +### `read_object` + +`read_object` expects an `ObjectReader` class which might come in several forms. But all +of these forms have a method with the following signature: + +```cpp +void read(const std::string_view& _name, + const InputVarType& _var) const noexcept; +``` + +Within your implementation of `read_object`, you must iterate through the object passed +to the function and then insert the resulting key-value-pairs into `object_reader.read`. diff --git a/docs/concepts/structs.md b/docs/concepts/structs.md new file mode 100644 index 00000000..ae96813d --- /dev/null +++ b/docs/concepts/structs.md @@ -0,0 +1,333 @@ +# Structs + +Structs can be set up as follows: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + std::vector children; +}; +``` + +You can initilize your struct like this: + +```cpp +const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .children = std::vector()}; +``` + +JSON uses camel case, but C++ uses snake case, so you might want to rename your fields: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + std::vector children; +}; +``` + + +You can also initialize fields in the struct declaration itself: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; +}; +``` + +Because you now have explicitly set this field, you do not have to do this every time: + +```cpp +const auto bart = Person{.first_name = "Bart"}; + +const auto lisa = Person{.first_name = "Lisa"}; + +const auto maggie = Person{.first_name = "Maggie"}; + +const auto homer = Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + +``` + +You can write this to a JSON string: + +```cpp +const auto json_string = rfl::json::write(homer); +``` + +```json +{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson","children":[]},{"firstName":"Lisa","lastName":"Simpson","children":[]},{"firstName":"Maggie","lastName":"Simpson","children":[]}]} +``` + +And you can parse it back into a struct: + +```cpp +const auto homer = rfl::json::read(json_string).value(); +``` + +## Important note + +**Do not create custom constructors on the structs.** + +reflect-cpp needs to be able to create the structs like this: + +```cpp +Person{"Bart", "Simpson", ...}; +``` + +But if you create a custom constructor, then C++ will no longer allow this kind of constructions. + +If you want to create the struct from one of your classes (the most like reason, you want to create custom constructors in the first place), +you might want to check out the section on [custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) or [custom parsers](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md). + + +## Utility functions + +### `rfl::as` + +`rfl::as` allows you to cast structs as other structs. This is useful if the fields in `B` are a subset of the fields in `A` +or we need the fields in `A` and `B` to produce `C`. + +This only works for the `rfl::Field`-syntax. + +For example: + +```cpp +struct A { + std::string f1; + std::string f2; +}; + +struct B { + std::string f3; + std::string f4; +}; + +struct C { + std::string f1; + std::string f2; + std::string f4; +}; + +const auto a = A{.f1 = "Hello", .f2 = "World"}; + +const auto b = B{.f3 = "Hello", .f4 = "World"}; + +// Creates c by retrieving f1 and f2 from a and f4 from b. +// Ignores f3. +const auto c = rfl::as(a, b); +``` + +In this case, `f1`, `f2` and `f4` are now copied into the newly created `c` of type `C`. + +Much like `rfl::replace`, `rfl::as` supports move semantics: + +```cpp +auto a = A{.f1 = "Hello", .f2 = "World"}; + +auto b = B{.f3 = "Hello", .f4 = "World"}; + +const auto c = rfl::as(std::move(a), std::move(b)); +``` + +In this case, `f1`, `f2` and `f4` are now moved into the newly created `c` of type `C`. This is a zero-copy operation. `f3` is discarded. + +`rfl::as` also supports `rfl::Flatten`. For instance: + +```cpp +struct A { + std::string f1; + std::string f2; +}; + +struct B { + std::string f3; + std::string f4; +}; + +struct C { + rfl::Flatten a; + rfl::Flatten b; + int f5; +}; + +const auto a = A{.f1 = "Hello", .f2 = "World"}; + +const auto b = B{.f3 = "Hello", .f4 = "World"}; + +const auto c = + rfl::as(a, b, rfl::make_field<"f5">(5)); +``` + +In this particular instance, `rfl::as(...)` is basically equivalent to this: + +```cpp +const auto c = C{.a = a, .b = b, .f5 = rfl::make_field<"f5">(5)}; +``` + +### `rfl::replace` + +`rfl::replace` creates a deep copy of the original struct or moves the original struct, replacing one or several fields in the process. + +This only works for the `rfl::Field`-syntax. + +In some cases, we really only want to change one or a few fields, to get from one struct to another: + +```cpp +const auto lisa = Person{ + .first_name = "Lisa", + .last_name = "Simpson", + .children = std::vector() +}; + +// Returns a deep copy of the original object, +// replacing first_name. +const auto maggie = + rfl::replace(lisa, rfl::make_field<"first_name">(std::string("Maggie"))); +``` + +`maggie` is now a deep copy of `lisa`, but with a new `first_name`. + +However, in some cases, we do not want or are unable to create a deep copy of a struct. + +For instance, suppose we had put the field `children` into a `rfl::Box`: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Box> children; +}; +``` + +`rfl::Box` cannot be copied, and if we naively try to apply `rfl::replace` to this, +this will not compile (disabling copies is very much the point of `rfl::Box`). + +However, we can use `std::move`: + +```cpp +auto lisa = Person{.first_name = "Lisa", + .last_name = "Simpson", + .children = rfl::make_box>()}; + +const auto maggie = rfl::replace( + std::move(lisa), rfl::make_field<"firstName">(std::string("Maggie"))); +``` + +The fields from `lisa` have now been moved into `maggie`. + +We can also remove several fields using `replace`: + +```cpp +auto lisa = Person{.first_name = "Lisa", + .last_name = "Simpson", + .children = rfl::make_box>()}; + +const auto milhouse = rfl::replace( + std::move(lisa), + rfl::make_field<"firstName">(std::string("Maggie")), + rfl::make_field<"lastName">(std::string("Van Houten"))); +``` + +If you have nested structs using `rfl::Flatten`, you can treat the fields inside `rfl::Flatten` +as if they were on the main level: + +```cpp +struct Person { + std::string first_name; + rfl::Box last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Box employer; + float salary; +}; + +auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = rfl::make_box("Simpson"), + .age = 45}, + .employer = rfl::make_box("Mr. Burns"), + .salary = 60000.0}; + +auto employee2 = + rfl::replace(std::move(employee), rfl::make_field<"salary">(70000.0), + rfl::make_field<"age">(46)); +```` + +In this case `age` is part of `Person` and `salary` part ot `Employee`, but +because you have flattened them, you can treat them as if they were on +the same level. + +You can also replace structs with other structs. Consider the following example: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = + Person{.first_name = "Homer", .last_name = "Simpson", .age = 45}, + .employer = std::string("Mr. Burns"), + .salary = 60000.0}; + +const auto carl = Person{.first_name = "Carl", .last_name = "", .age = 45}; + +const auto employee2 = rfl::replace(employee, carl); +``` + +This code flattens the employee structs and then replaces all relevant fields with their counterparts contained in `carl`. + +Finally, we get this JSON string: + +```json +{"first_name":"Carl","last_name":"","age":45,"employer":"Mr. Burns","salary":60000.0} +``` + +Don't worry, this is fairly optimized and makes heavy use of forwarding. It does not make any copies than it absolutely has to. + +### `rfl::to_view` + +`rfl::to_view` allows you to create views on structs using which you can access an modify the fields of the structs just like a tuple. + +Under-the-hood, a view is a `rfl::NamedTuple` containing pointers to the original fields. + +For example: + +```cpp +auto lisa = Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8}; + +const auto view = rfl::to_view(lisa); + +// Assigns the first field, thus modifying the struct 'lisa'. +*view.get<0>() = "Maggie"; + +// view.values() is a std::tuple containing +// pointers to the original fields. +*std::get<1>(view.values()) = "Simpson"; + +// You can also access fields by their name. +// The correctness will be ensured at compile time. +*view.get<"age">() = 0; + +// You can also access fields like this. +*rfl::get<0>(view) = "Maggie"; + +// Or like this. +*rfl::get<"first_name">(view) = "Maggie"; +``` diff --git a/docs/concepts/supported_formats.md b/docs/concepts/supported_formats.md new file mode 100644 index 00000000..691f1751 --- /dev/null +++ b/docs/concepts/supported_formats.md @@ -0,0 +1,615 @@ +## BSON + +For BSON support, you must also include the header `` and link to the libbson library (https://github.com/mongodb/libbson). + +Like the name implies, BSON is a JSON-like binary format. It is most notably used by MongoDB. + +### Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `person` can be serialized like this: + +```cpp +const auto person = Person{...}; +const auto bytes = rfl::bson::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::bson::read(bytes); +``` + +You can also parse raw pointers (either `const char*` or `const uint8_t*`): + +```cpp +const rfl::Result result = rfl::bson::read(ptr, length); +``` + +### Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::bson::load("/path/to/file.bson"); + +const auto person = Person{...}; +rfl::bson::save("/path/to/file.bson", person); +``` + +### Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::bson::read(my_istream); + +const auto person = Person{...}; +rfl::bson::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::bson::write(person, std::cout) << std::endl; +``` + +(Since BSON is a binary format, the readability of this will be limited, but it might be useful for debugging). + +### 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 BSON format, these must be a static function on your struct or class called +`from_bson` that take a `rfl::bson::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::bson::Reader::InputVarType; + static rfl::Result from_bson(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_bson` as follows: + +```cpp +rfl::Result Person::from_bson(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::bson::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the BSON parsing when the source file is compiled. + +## CBOR + +For CBOR support, you must also include the header `` and link to the tinycbor library (https://github.com/intel/tinycbor). + +CBOR or Concise Binary Object Representation, is a JSON-like binary format with an emphasis on small binary sizes. + +### Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `Person` can be turned into a bytes vector like this: + +```cpp +const auto person = Person{...}; +const std::vector bytes = rfl::cbor::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::cbor::read(bytes); +``` + +### Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::cbor::load("/path/to/file.cbor"); + +const auto person = Person{...}; +rfl::cbor::save("/path/to/file.cbor", person); +``` + +### Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::cbor::read(my_istream); + +const auto person = Person{...}; +rfl::cbor::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::cbor::write(person, std::cout) << std::endl; +``` + +(Since CBOR is a binary format, the readability of this will be limited, but it might be useful for debugging). + +### 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 CBOR format, these must be a static function on your struct or class called +`from_cbor` that take a `rfl::cbor::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::cbor::Reader::InputVarType; + static rfl::Result from_cbor(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_cbor` as follows: + +```cpp +rfl::Result Person::from_cbor(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::cbor::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the CBOR parsing when the source file is compiled. + +## JSON + +For JSON support, you must also include the header ``. + +### Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +You can parse JSON strings like this: + +```cpp +const rfl::Result result = rfl::json::read(json_string); +``` + +A `Person` struct can be serialized like this: + +```cpp +const auto person = Person{...}; +const std::string json_string = rfl::json::write(person); +``` + +If you want a "pretty" JSON representation, you can do this: + +```cpp +const std::string json_string = rfl::json::write(person, rfl::json::pretty); +``` + +### 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); +``` + +`rfl::json::pretty` will work here as well: + +```cpp +rfl::json::save("/path/to/file.json", person, rfl::json::pretty); +``` + +### Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::json::read(my_istream); + +const auto person = Person{...}; +rfl::json::write(person, my_ostream); +``` + +`rfl::json::pretty` will work here as well: + +```cpp +rfl::json::write(person, my_ostream, rfl::json::pretty); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::json::write(person, std::cout) << std::endl; +``` + +### 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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + 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. + +## JSON schema + +JSON schemata are a powerful tool for expressing the expected structure of your input. You can use it to validate your input before you even send it to your C++ backend, which will result in better UX. + +It can also be used for code generation. For instance, tools such as https://app.quicktype.io/ allow you to generate code in multiple programming languages from the JSON schema (even though the validations are usually omitted). + +If you are interacting with Python, we warmly recommend https://docs.pydantic.dev/latest/integrations/datamodel_code_generator/. This allows you to generate Pydantic dataclasses, including the validation, from the JSON schema. + +Note that this is only supported for JSON, not for other formats. + +### Basic idea + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Email email; + std::vector children; + float salary; +}; +``` + +You can generate a JSON schema like this: + +```cpp +const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); +``` + +You do not have to pass `rfl::json::pretty`, but for the purposes of this documentation it is better to do so. + +This will result in the following JSON schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` + +You can insert this into the tools mentioned above and see the generated code. + +### Adding descriptions + +JSON schemata also often contain descriptions. reflect-cpp supports this as well. + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Description<"Must be a proper email in the form xxx@xxx.xxx.", + rfl::Email> + email; + rfl::Description< + "The person's children. Pass an empty array for no children.", + std::vector> + children; + float salary; +}; +``` + +```cpp +const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); +``` + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "description": "The person's children. Pass an empty array for no children.", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "description": "Must be a proper email in the form xxx@xxx.xxx.", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` + +You also add a description to the entire JSON schema: + +```cpp +const std::string json_schema = rfl::json::to_schema< + rfl::Description<"JSON schema that describes the required " + "attributes for the person class.", + Person>>(rfl::json::pretty); +``` + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "description": "JSON schema that describes the required attributes for the person class.", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "description": "The person's children. Pass an empty array for no children.", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "description": "Must be a proper email in the form xxx@xxx.xxx.", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` + +## YAML + +For YAML support, you must also include the header `` and include the yaml-cpp library (https://github.com/jbeder/yaml-cpp) in your project. + +### Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +You can parse YAML strings like this: + +```cpp +const rfl::Result result = rfl::yaml::read(yaml_string); +``` + +A `Person` can be serialized like this: + +```cpp +const auto person = Person{...}; +const std::string yaml_string = rfl::yaml::write(person); +``` + +### Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::yaml::load("/path/to/file.yml"); + +const auto person = Person{...}; +rfl::yaml::save("/path/to/file.yml", person); +``` + +### Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::yaml::read(my_istream); + +const auto person = Person{...}; +rfl::yaml::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::yaml::write(person, std::cout) << std::endl; +``` + +### 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 YAML format, these must be a static function on your struct or class called +`from_yaml_obj` that take a `rfl::yaml::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using YAMLVar = typename rfl::yaml::Reader::InputVarType; + static rfl::Result from_yaml_obj(const YAMLVar& _obj); +}; +``` + +And in your source file, you implement `from_yaml_obj` as follows: + +```cpp +rfl::Result Person::from_yaml_obj(const YAMLVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::yaml::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the YAML parsing when the +source file is compiled. + diff --git a/docs/concepts/supported_formats/bson.md b/docs/concepts/supported_formats/bson.md new file mode 100644 index 00000000..4f800941 --- /dev/null +++ b/docs/concepts/supported_formats/bson.md @@ -0,0 +1,106 @@ +# BSON + +For BSON support, you must also include the header `` and link to the libbson library (https://github.com/mongodb/libbson). + +Like the name implies, BSON is a JSON-like binary format. It is most notably used by MongoDB. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `person` can be serialized like this: + +```cpp +const auto person = Person{...}; +const auto bytes = rfl::bson::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::bson::read(bytes); +``` + +You can also parse raw pointers (either `const char*` or `const uint8_t*`): + +```cpp +const rfl::Result result = rfl::bson::read(ptr, length); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::bson::load("/path/to/file.bson"); + +const auto person = Person{...}; +rfl::bson::save("/path/to/file.bson", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::bson::read(my_istream); + +const auto person = Person{...}; +rfl::bson::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::bson::write(person, std::cout) << std::endl; +``` + +(Since BSON is a binary format, the readability of this will be limited, but it might be useful for debugging). + +## 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 BSON format, these must be a static function on your struct or class called +`from_bson` that take a `rfl::bson::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::bson::Reader::InputVarType; + static rfl::Result from_bson(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_bson` as follows: + +```cpp +rfl::Result Person::from_bson(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::bson::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the BSON parsing when the source file is compiled. diff --git a/docs/concepts/supported_formats/cbor.md b/docs/concepts/supported_formats/cbor.md new file mode 100644 index 00000000..c64a1d91 --- /dev/null +++ b/docs/concepts/supported_formats/cbor.md @@ -0,0 +1,100 @@ +# CBOR + +For CBOR support, you must also include the header `` and link to the tinycbor library (https://github.com/intel/tinycbor). + +CBOR or Concise Binary Object Representation, is a JSON-like binary format with an emphasis on small binary sizes. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `Person` can be turned into a bytes vector like this: + +```cpp +const auto person = Person{...}; +const std::vector bytes = rfl::cbor::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::cbor::read(bytes); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::cbor::load("/path/to/file.cbor"); + +const auto person = Person{...}; +rfl::cbor::save("/path/to/file.cbor", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::cbor::read(my_istream); + +const auto person = Person{...}; +rfl::cbor::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::cbor::write(person, std::cout) << std::endl; +``` + +(Since CBOR is a binary format, the readability of this will be limited, but it might be useful for debugging). + +## 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 CBOR format, these must be a static function on your struct or class called +`from_cbor` that take a `rfl::cbor::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::cbor::Reader::InputVarType; + static rfl::Result from_cbor(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_cbor` as follows: + +```cpp +rfl::Result Person::from_cbor(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::cbor::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the CBOR parsing when the source file is compiled. diff --git a/docs/concepts/supported_formats/flexbuffers.md b/docs/concepts/supported_formats/flexbuffers.md new file mode 100644 index 00000000..864171cf --- /dev/null +++ b/docs/concepts/supported_formats/flexbuffers.md @@ -0,0 +1,246 @@ +# Flexbuffers + +For flexbuffers support, you must also include the header `` and link to the flatbuffers library (https://github.com/google/flatbuffers). + +Flexbuffers is part of the flatbuffers library, which is a binary format developed by Google. + +reflect-cpp can be used on top of flexbuffers. To see how this is advantageous, consider the following example: + +## Simple example + +```cpp +#include +#include + +using Color = rfl::Literal<"Red", "Green", "Blue">; + +struct Weapon { + std::string name; + short damage; +}; + +using Equipment = rfl::Variant>; + +struct Vec3 { + float x; + float y; + float z; +}; + +struct Monster { + Vec3 pos; + short mana = 150; + short hp = 100; + std::string name; + bool friendly = false; + std::vector inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; +}; + +const auto sword = Weapon{.name = "Sword", .damage = 3}; +const auto axe = Weapon{.name = "Axe", .damage = 5}; + +const auto weapons = std::vector({sword, axe}); + +const auto position = Vec3{1.0f, 2.0f, 3.0f}; + +const auto inventory = + std::vector({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + +const auto orc = Monster{.pos = position, + .mana = 150, + .hp = 80, + .name = "MyMonster", + .inventory = inventory, + .color = Color::make<"Red">(), + .weapons = weapons, + .equipped = rfl::make_field<"weapon">(axe)}; + +const auto bytes = rfl::flexbuf::write(orc); + +const auto res = rfl::flexbuf::read(bytes); +``` + +## For comparison: Standard flatbuffers + +Let's talk about what normal flatbuffers would make you do to set up this example. + +First of all, you would have to set up your `Monster.fbs`: + +``` +namespace MyGame.Sample; + +enum Color:byte { Red = 0, Green, Blue = 2 } + +union Equipment { Weapon } // Optionally add more tables. + +struct Vec3 { + x:float; + y:float; + z:float; +} + +table Monster { + pos:Vec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated); + inventory:[ubyte]; + color:Color = Blue; + weapons:[Weapon]; + equipped:Equipment; + path:[Vec3]; +} + +table Weapon { + name:string; + damage:short; +} + +root_type Monster; +``` + +Then you would have to generate the C++ code using the flatbuffers compiler. + +Finally, here is the code that you would then write afterwards: + +```cpp +// Build up a serialized buffer algorithmically: +flatbuffers::FlatBufferBuilder builder; + +// First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'. +auto weapon_one_name = builder.CreateString("Sword"); +short weapon_one_damage = 3; + +auto weapon_two_name = builder.CreateString("Axe"); +short weapon_two_damage = 5; + +// Use the `CreateWeapon` shortcut to create Weapons with all fields set. +auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); +auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); + +// Create a FlatBuffer's `vector` from the `std::vector`. +std::vector> weapons_vector; +weapons_vector.push_back(sword); +weapons_vector.push_back(axe); +auto weapons = builder.CreateVector(weapons_vector); + +// Second, serialize the rest of the objects needed by the Monster. +auto position = Vec3(1.0f, 2.0f, 3.0f); + +auto name = builder.CreateString("MyMonster"); + +unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; +auto inventory = builder.CreateVector(inv_data, 10); + +// Shortcut for creating monster with all fields set: +auto orc = CreateMonster(builder, &position, 150, 80, name, inventory, + Color_Red, weapons, Equipment_Weapon, axe.Union()); + +builder.Finish(orc); // Serialize the root of the object. +``` + +I think it should be fairly obvious that using reflect-cpp on top drastically reduces the amount of boilerplate code. + + +But what it more, unlike "normal" flatbuffers, flexbuffers also supports field names. Field names make it a lot easier to maintain backwards compatability. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `person` can be turned into a bytes vector like this: + +```cpp +const auto person = Person{...}; +const auto bytes = rfl::flexbuf::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::flexbuf::read(bytes); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::flexbuf::load("/path/to/file.fb"); + +const auto person = Person{...}; +rfl::flexbuf::save("/path/to/file.fb", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::flexbuf::read(my_istream); + +const auto person = Person{...}; +rfl::flexbuf::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::flexbuf::write(person, std::cout) << std::endl; +``` + +(Since flexbuffers is a binary format, the readability of this will be limited, but it might be useful for debugging). + +## 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 flexbuffers format, these must be a static function on your struct or class called +`from_flexbuf` that take a `rfl::flexbuf::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::flexbuf::Reader::InputVarType; + static rfl::Result from_flexbuf(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_flexbuf` as follows: + +```cpp +rfl::Result Person::from_flexbuf(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::flexbuf::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the flexbuffers parsing when the +source file is compiled. diff --git a/docs/concepts/supported_formats/json.md b/docs/concepts/supported_formats/json.md new file mode 100644 index 00000000..ad0ca153 --- /dev/null +++ b/docs/concepts/supported_formats/json.md @@ -0,0 +1,116 @@ +# JSON + +For JSON support, you must also include the header ``. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +You can parse JSON strings like this: + +```cpp +const rfl::Result result = rfl::json::read(json_string); +``` + +A `Person` struct can be serialized like this: + +```cpp +const auto person = Person{...}; +const std::string json_string = rfl::json::write(person); +``` + +If you want a "pretty" JSON representation, you can do this: + +```cpp +const std::string json_string = rfl::json::write(person, rfl::json::pretty); +``` + +## 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); +``` + +`rfl::json::pretty` will work here as well: + +```cpp +rfl::json::save("/path/to/file.json", person, rfl::json::pretty); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::json::read(my_istream); + +const auto person = Person{...}; +rfl::json::write(person, my_ostream); +``` + +`rfl::json::pretty` will work here as well: + +```cpp +rfl::json::write(person, my_ostream, rfl::json::pretty); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::json::write(person, std::cout) << std::endl; +``` + +## 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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + 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/concepts/supported_formats/json_schema.md b/docs/concepts/supported_formats/json_schema.md new file mode 100644 index 00000000..6c995155 --- /dev/null +++ b/docs/concepts/supported_formats/json_schema.md @@ -0,0 +1,192 @@ +# JSON schema + +JSON schemata are a powerful tool for expressing the expected structure of your input. You can use it to validate your input before you even send it to your C++ backend, which will result in better UX. + +It can also be used for code generation. For instance, tools such as https://app.quicktype.io/ allow you to generate code in multiple programming languages from the JSON schema (even though the validations are usually omitted). + +If you are interacting with Python, we warmly recommend https://docs.pydantic.dev/latest/integrations/datamodel_code_generator/. This allows you to generate Pydantic dataclasses, including the validation, from the JSON schema. + +Note that this is only supported for JSON, not for other formats. + +## Basic idea + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Email email; + std::vector children; + float salary; +}; +``` + +You can generate a JSON schema like this: + +```cpp +const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); +``` + +You do not have to pass `rfl::json::pretty`, but for the purposes of this documentation it is better to do so. + +This will result in the following JSON schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` + +You can insert this into the tools mentioned above and see the generated code. + +## Adding descriptions + +JSON schemata also often contain descriptions. reflect-cpp supports this as well. + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Description<"Must be a proper email in the form xxx@xxx.xxx.", + rfl::Email> + email; + rfl::Description< + "The person's children. Pass an empty array for no children.", + std::vector> + children; + float salary; +}; +``` + +```cpp +const std::string json_schema = rfl::json::to_schema(rfl::json::pretty); +``` + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "description": "The person's children. Pass an empty array for no children.", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "description": "Must be a proper email in the form xxx@xxx.xxx.", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` + +You also add a description to the entire JSON schema: + +```cpp +const std::string json_schema = rfl::json::to_schema< + rfl::Description<"JSON schema that describes the required " + "attributes for the person class.", + Person>>(rfl::json::pretty); +``` + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/Person", + "description": "JSON schema that describes the required attributes for the person class.", + "definitions": { + "Person": { + "type": "object", + "properties": { + "children": { + "type": "array", + "description": "The person's children. Pass an empty array for no children.", + "items": { + "$ref": "#/definitions/Person" + } + }, + "email": { + "type": "string", + "description": "Must be a proper email in the form xxx@xxx.xxx.", + "pattern": "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "salary": { + "type": "number" + } + }, + "required": [ + "children", + "email", + "first_name", + "last_name", + "salary" + ] + } + } +} +``` diff --git a/docs/concepts/supported_formats/supporting_your_own_format.md b/docs/concepts/supported_formats/supporting_your_own_format.md new file mode 100644 index 00000000..24deb053 --- /dev/null +++ b/docs/concepts/supported_formats/supporting_your_own_format.md @@ -0,0 +1,258 @@ +# 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 = ...; + + /// Sets an empty array as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `_size`. Returns the new array for further modification. + OutputArrayType array_as_root(const size_t _size) const noexcept; + + /// Sets an empty object as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `_size`. + /// Returns the new object for further modification. + OutputObjectType object_as_root(const size_t _size) const noexcept; + + /// Sets a null as the root element of the document. Returns OutputVarType + /// containing the null value. + OutputVarType null_as_root() const noexcept; + + /// Sets a basic value (bool, numeric, string) as the root element of the + /// document. Returns an OutputVarType containing the new value. + template + OutputVarType value_as_root(const T& _var) const noexcept; + + /// Adds an empty array to an existing array. Returns the new + /// array for further modification. + OutputArrayType add_array_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + /// Adds an empty array to an existing object. The key or name of the field is + /// signified by `_name`. Returns the new array for further modification. + OutputArrayType add_array_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + /// Adds an empty object to an existing array. Returns the new + /// object for further modification. + OutputObjectType add_object_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept; + + /// Adds an empty object to an existing object. The key or name of the field + /// is signified by `_name`. Returns the new object for further modification. + OutputObjectType add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an array. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_array(const T& _var, + OutputArrayType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an existing object. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_object(const std::string_view& _name, const T& _var, + OutputObjectType* _parent) const noexcept; + + /// Adds a null value to an array. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept; + + /// Adds a null value to an existing object. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + /// Signifies to the writer that we do not want to add any further elements to + /// this array. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + void end_array(OutputArrayType* _arr) const noexcept; + + /// Signifies to the writer that we do not want to add any further elements to + /// this object. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + void end_object(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 {...} + + /// 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 inserts the values into the array + /// reader. See below for a more detailed explanation. + template + std::optional read_array(const ArrayReader& _array_reader, + const InputArrayType& _arr) const noexcept {...} + + /// Iterates through an object and inserts the key-value pairs into the object + /// reader. See below for a more detailed explanation. + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) 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, `read_array` and `read_object` probably require further explanation. + +## `read_array` + +`read_array` expects an `ArrayReader` class which might come in several forms. But all +of these forms have a method with the following signature: + +```cpp +std::optional read(const InputVarType& _var) const noexcept; +``` + +Within your implementation of `read_array`, you must iterate through the array passed +to the function and then insert the resulting values into `array_reader.read`. If +`array_reader.read` returns an error, then you must return that error immediately. + +## `read_object` + +`read_object` expects an `ObjectReader` class which might come in several forms. But all +of these forms have a method with the following signature: + +```cpp +void read(const std::string_view& _name, + const InputVarType& _var) const noexcept; +``` + +Within your implementation of `read_object`, you must iterate through the object passed +to the function and then insert the resulting key-value-pairs into `object_reader.read`. diff --git a/docs/concepts/supported_formats/toml.md b/docs/concepts/supported_formats/toml.md new file mode 100644 index 00000000..52d05ff8 --- /dev/null +++ b/docs/concepts/supported_formats/toml.md @@ -0,0 +1,98 @@ +# TOML + +For TOML support, you must also include the header `` and include the toml++ library (https://github.com/marzer/tomlplusplus) in your project. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +You can parse TOML strings like this: + +```cpp +const rfl::Result result = rfl::toml::read(toml_string); +``` + +A `person` can be serialized like this: + +```cpp +const auto person = Person{...}; +const std::string toml_string = rfl::toml::write(person); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::toml::load("/path/to/file.toml"); + +const auto person = Person{...}; +rfl::toml::save("/path/to/file.toml", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::toml::read(my_istream); + +const auto person = Person{...}; +rfl::toml::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::toml::write(person, std::cout) << std::endl; +``` + +## 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 TOML format, these must be a static function on your struct or class called +`from_toml_obj` that take a `rfl::toml::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using TOMLVar = typename rfl::toml::Reader::InputVarType; + static rfl::Result from_toml_obj(const TOMLVar& _obj); +}; +``` + +And in your source file, you implement `from_toml_obj` as follows: + +```cpp +rfl::Result Person::from_toml_obj(const TOMLVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::toml::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the TOML parsing when the +source file is compiled. + diff --git a/docs/concepts/supported_formats/xml.md b/docs/concepts/supported_formats/xml.md new file mode 100644 index 00000000..827c0f62 --- /dev/null +++ b/docs/concepts/supported_formats/xml.md @@ -0,0 +1,245 @@ +# XML + +For XML support, you must also include the header `` and include the pugixml library (https://github.com/zeux/pugixml) in your project. + +## Simple example + +Consider the following example: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector child; +}; + +const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + +const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + +const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + + + Homer + Simpson + Springfield + 1987-04-19 + 45 + homer@simpson.com + + Bart + Simpson + Springfield + 1987-04-19 + 10 + bart@simpson.com + + + Lisa + Simpson + Springfield + 1987-04-19 + 8 + lisa@simpson.com + + + Maggie + Simpson + Springfield + 1987-04-19 + 0 + maggie@simpson.com + + +``` + +Unlike most other formats, XML distinguishes between attributes and nodes. +If you want something to be displayed as an attribute, you must mark it as such: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", rfl::Attribute> first_name; + rfl::Rename<"lastName", rfl::Attribute> last_name = "Simpson"; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute age; + rfl::Attribute email; + std::vector child; +}; + +const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + +const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + +const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + + + + + + +``` + +Note that only boolean values, string values, integral values or floating point values can be represented as attributes. + +There also is a special field name called `xml_content` to be used when you want a value directly inserted into the content. +Again, only boolean values, string values, integral values or floating point values can be represented this way: + +```cpp +struct Person { + std::string xml_content; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute email; + std::vector child; +}; + +const auto bart = Person{.xml_content = "Bart Simpson", + .birthday = "1987-04-19", + .email = "bart@simpson.com"}; + +const auto lisa = Person{.xml_content = "Lisa Simpson", + .birthday = "1987-04-19", + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.xml_content = "Maggie Simpson", + .birthday = "1987-04-19", + .email = "maggie@simpson.com"}; + +const auto homer = Person{.xml_content = "Homer Simpson", + .birthday = "1987-04-19", + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + +Homer SimpsonBart Simpson + Lisa Simpson + Maggie Simpson + +``` + +## Limitations of the XML format + +### There must be exactly one root node + +The XML format requires that there must be exactly one root node. +Other formats, like JSON, allow you to have an array as the root element. XML disallows that. + +### The root node must have a name + +As you may have noticed, reflect-cpp uses the names of fields as the names of the XML nodes or attributes. +However, the root node does not have a field name associated with it. So reflect-cpp will use the name +of the struct as the name of the root node. This is a problem when the root node is a template parameter, +because the name of the root node cannot contain "<" or ">". + +In this case, you can explicitly set a root node name like this: + +```cpp +rfl::xml::write<"NameOfTheRootNode">(homer); +``` + +### No nested arrays + +Unlike JSON, XML doesn't have an explicit concept of arrays. Array-like structures are represented by simply +writing the same field over and over again (i.e. Homer's children in the examples above). + +This also implies that something like this cannot be properly represented in XML: + +```cpp +struct Person { + std::string name; + std::vector> child; +}; +``` + +There is no way to represent a vector of vectors in XML. It's a limitation of the format. + +### Integers cannot be tags + +In JSON, it is possible to represent a map with integers as keys like this: + +```cpp +std::map homer; +homer[1] = "Homer"; +homer[2] = "Simpson"; + +rfl::json::write(homer); +``` + +This will be represented as follows: + +```json +{"1":"Homer","2":"Simpson"} +``` + +In XML, this is impossible. The XML standard requires that the tag must not start with an integer. + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::xml::load("/path/to/file.xml"); + +const auto person = Person{...}; +rfl::xml::save("/path/to/file.xml", person); +``` + diff --git a/docs/concepts/supported_formats/yaml.md b/docs/concepts/supported_formats/yaml.md new file mode 100644 index 00000000..12589e1f --- /dev/null +++ b/docs/concepts/supported_formats/yaml.md @@ -0,0 +1,98 @@ +# YAML + +For YAML support, you must also include the header `` and include the yaml-cpp library (https://github.com/jbeder/yaml-cpp) in your project. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +You can parse YAML strings like this: + +```cpp +const rfl::Result result = rfl::yaml::read(yaml_string); +``` + +A `Person` can be serialized like this: + +```cpp +const auto person = Person{...}; +const std::string yaml_string = rfl::yaml::write(person); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::yaml::load("/path/to/file.yml"); + +const auto person = Person{...}; +rfl::yaml::save("/path/to/file.yml", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::yaml::read(my_istream); + +const auto person = Person{...}; +rfl::yaml::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::yaml::write(person, std::cout) << std::endl; +``` + +## 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 YAML format, these must be a static function on your struct or class called +`from_yaml_obj` that take a `rfl::yaml::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::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using YAMLVar = typename rfl::yaml::Reader::InputVarType; + static rfl::Result from_yaml_obj(const YAMLVar& _obj); +}; +``` + +And in your source file, you implement `from_yaml_obj` as follows: + +```cpp +rfl::Result Person::from_yaml_obj(const YAMLVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::yaml::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the YAML parsing when the +source file is compiled. + diff --git a/docs/concepts/types.md b/docs/concepts/types.md new file mode 100644 index 00000000..7f871298 --- /dev/null +++ b/docs/concepts/types.md @@ -0,0 +1,804 @@ + +## Boxes and References + +In previous sections, we have defined the `Person` class recursively: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + std::vector children; +}; +``` + +This works, because `std::vector` contains a pointer under-the-hood. But what wouldn't work is something like this: + +```cpp +// WILL NOT COMPILE +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + Person child; +}; +``` + +This is because the compiler cannot figure out the intended size of the struct. But recursively defined structures +are important. For instance, if you deal with machine learning, you might be familiar with a decision tree. + +A decision tree consists of a `Leaf` containing the prediction and a `Node` which splits the decision tree into +two subtrees. + +A naive implementation might look like this: + +```cpp +// WILL NOT COMPILE +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double prediction; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + DecisionTree lesser; + DecisionTree greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; +``` + +Again, this will not compile, because the compiler cannot figure out the intended size of the struct. + +A possible solution might be to use `std::unique_ptr`: + +```cpp +// Will compile, but not an ideal design. +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double prediction; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + std::unique_ptr lesser; + std::unique_ptr greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; +``` + +This will compile, but the design is less than ideal. We know for a fact that a `Node` must have +exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields +"lesser" and "greater" are marked optional and you will have to check at runtime that they are indeed set. + +But this violates the principles of reflection. Reflection is all about validating as much of our assumptions +upfront as we possibly can. For a great theoretical discussion of this topic, check out +[Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) +by Alexis King. + +So how would we encode our assumptions that the fields "lesser" and "greater" must exist in the type system and +still have code that compiles? By using `rfl::Box` instead of `std::unique_ptr`: + +```cpp +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double prediction; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Box lesser; + rfl::Box greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; +``` + +`rfl::Box` is a thin wrapper around `std::unique_ptr`, but it is guaranteed to **never be null** (unless you do something egregious such as trying to access it after calling `std::move`). It is a `std::unique_ptr` without the `nullptr`. + +If you want to learn more about the evils of null references, check out the +[Null References: The Billion Dollar Mistake](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/) +by Tony Hoare, who invented the concept in the first place. + +You **must** initialize `rfl::Box` the moment you create it and it cannot be dereferenced until it is destroyed. + +`rfl::Box` can be initialized using `rfl::make_box<...>(...)`, just like `std::make_unique<...>(...)`: + +```cpp +auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + +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)}; + +const DecisionTree tree{.leaf_or_node = std::move(node)}; + +const auto json_string = rfl::json::write(tree); +``` + +This will result in the following JSON string: + +```json +{"leafOrNode":{"type":"Node","criticalValue":10.0,"lesser":{"leafOrNode":{"type":"Leaf","value":3.0}},"greater":{"leafOrNode":{"type":"Leaf","value":5.0}}}} +``` + +You can also initialize `rfl::Box` from a `std::unique_ptr`: + +```cpp +auto ptr = std::make_unique("Hello World!"); +const rfl::Result> box = rfl::make_box(std::move(ptr)); +``` + +Note that `box` is wrapped in a `Result`. That is, because we cannot guarantee at compile time +that `ptr` is not `nullptr`, therefore we need to account for that. + +If you want to use reference-counted pointers, instead of unique pointers, you can use `rfl::Ref`. +`rfl::Ref` is the same concept as `rfl::Box`, but using `std::shared_ptr` under-the-hood. + +```cpp +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Ref lesser; + rfl::Ref greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +const auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + +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)}; + +const DecisionTree tree{.leaf_or_node = std::move(node)}; + +const auto json_string = rfl::json::write(tree); +``` + +The resulting JSON string is identical: + +```json +{"leafOrNode":{"type":"Node","criticalValue":10.0,"lesser":{"leafOrNode":{"type":"Leaf","value":3.0}},"greater":{"leafOrNode":{"type":"Leaf","value":5.0}}}} +``` + +## Enums + +reflect-cpp supports scoped enumerations. They can either come in the form of normal enumerations or flag enums. + +### Normal enumerations + +Example: + +```cpp +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +const auto circle = Circle{.radius = 2.0, .color = Color::green}; + +rfl::json::write(circle); +``` + +This results in the following JSON string: + +```json +{"radius":2.0,"color":"green"} +``` + +However, some limitations apply: + +1. They must be be scoped enumerations. + +```cpp +/// OK - scoped enumeration +enum class Color1 { red, green, blue, yellow }; + +/// OK - scoped enumeration +enum struct Color2 { red, green, blue, yellow }; + +/// unsupported - unscoped enumerations +enum Color3 { red, green, blue, yellow }; +``` + +2. You cannot have more than 128 values and if you explicitly assign values, they must be between 0 and 127. + +```cpp +/// OK +enum class Color1 { red, green, blue, yellow }; + +/// OK +enum struct Color2 { red, green, blue = 50, yellow }; + +/// unsupported - red is a negative value +enum Color3 { red = -10, green, blue, yellow }; + +/// unsupported - red is greater than 127 +enum Color3 { red = 200, green, blue, yellow }; +``` + +### Flag enums + +Sometimes the enumerations are not mutually exclusive - sticking with the metaphor of colors, it is perfectly +possible for things to have more than one color. C++ programmers sometimes like to model this using a flag enum. + +Flag enums work as follows: + +1. The bitwise OR operator must be defined on them. If an enum has the bitwise OR operator defined on it, it will be treated as a flag enum. +2. The most important values of the enum must be 1 or 2^N, N being a positive integer (in other words 1,2,4,8,16,32,...). + +Example: + +```cpp +// The important colors must be 1 or 2^N +enum class Color { + red = 256, + green = 512, + blue = 1024, + yellow = 2048, + orange = (256 | 2048) // red + yellow = orange +}; + +// The bitwise OR operator must be defined - this is how reflect-cpp knows that +// this is a flag enum. +inline Color operator|(Color c1, Color c2) { + return static_cast(static_cast(c1) | static_cast(c2)); +} +``` + +In this particular example, the important colors red, green, blue and yellow are all in the form of 2^N. +Other colors are ok as well, if they are expressed as combinations of the 2^N-colors. + +When something is a flag enum, then you can also do this: + +```cpp +const auto circle = + Circle{.radius = 2.0, .color = Color::blue | Color::green}; +``` + +Which will then be represented as follows: + +```json +{"radius":2.0,"color":"blue|green"} +``` + +Using orange is fine as well: + +```cpp +const auto circle = + Circle{.radius = 2.0, .color = Color::orange}; +``` + +But it will be represented in terms of the base colors (which are in the form 2^N): + +```json +{"radius":2.0,"color":"red|yellow"} +``` + +You can also combine orange with another color: + +```cpp +const auto circle = + Circle{.radius = 2.0, .color = Color::blue | Color::orange}; +``` + +Which will result in this: + +```json +{"radius":2.0,"color":"red|blue|yellow"} +``` + +### What happens if an enum cannot be matched? + +If an enum cannot be matched, it will be written as an integer. This works for both normal enums as well as flag enums. + +For instance, if you use the `Color` flag enum as described in the previous section, you can do something like this: + +```cpp +// Enums are not supposed to be used like this, but it is defined behavior for scoped enumerations. +const auto circle = Circle{.radius = 2.0, .color = static_cast(10000)}; +``` + +This will be represented as follows: + +```json +{"radius":2.0,"color":"16|red|green|blue|8192"} +``` + +This works, because 16 + 256 + 512 + 1024 + 8192 = 10000. Flag enums are *always* represented in terms of 2^N-numbers. + +### General-purpose enumeration utilities + +reflect-cpp also allows you to directly convert between enumerator values and strings: + +```cpp +enum class Color { red, green, blue }; + +auto name = rfl::enum_to_string(Color::red); // "red" +auto value = rfl::string_to_enum("red"); // result containing Color::red +auto value = rfl::string_to_enum("greem"); // error result +``` + +This works with normal and flag enums, and behaves just like serialization of types containing enumerations as described above. + +You can also inspect the defined enumerators of an enum type (including at compile-time): + +```cpp +enum class Color { red, green, blue }; + +// This produces a named tuple where the keys are "red", "green", and "blue", with corresponding +// values Color::red, Color::green, and Color::blue. +auto enumerators_named_tuple = rfl::get_enumerators(); + +// You can iterate over the enumerators like this: +enumerators_named_tuple.apply([&](const auto& field) { + // field.name() will be "red", "green", "blue" + // field.value() will be Color::red, Color::green, Color::blue +}); + +// This produces the same data as an std::array containing std::pair, +// which can be inspected at compile-time. +constexpr auto enumerator_array = rfl::get_enumerator_array(); +``` + +In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, +there is also `rfl::get_underlying_enumerators()` and `rfl::get_underlying_enumerator_array()`. + +## Literals + +In many cases, when you have strings, you know in advance that these strings can only +assume a limited number of values. For reasons of efficiency and safety, it is a good +idea to use Literals instead of strings. + +You can declare a Literal as follows: + +```cpp +using MyLiteral = rfl::Literal<"option1", "option2", ...>; +``` + +You can construct literals as follows: + +```cpp +const auto my_literal = MyLiteral::make<"option1">(); +``` + +Literals that contain only one option also have a default constructor. + +Literals can be used inside switches: + +```cpp +switch(my_literal.value()) { + case MyLiteral::value_of<"option1">(): + ... + + case MyLiteral::value_of<"option2">(): + ... + + ... +} +``` + +Literals are stored as `uint8_t` or `uint16_t` under-the-hood. But you can extract their name as a string using `.name()` +or the underlying value using `.value()`. + +```cpp +using MyLiteral = rfl::Literal<"option1", "option2", ...>; + +const auto my_literal = MyLiteral::make<"option1">(); + +// Prints "option1" +std::cout << my_literal.name() << std::endl; + +// Prints "0" +std::cout << my_literal.value() << std::endl; +``` + +**Example** + +```cpp +// There are only five Simpsons. +using FirstName = rfl::Literal<"Homer", "Marge", "Bart", "Lisa", "Maggie">; + +// All Simpsons have the last name. +using LastName = rfl::Literal<"Simpson">; + +struct Person { + rfl::Rename<"firstName", FirstName> first_name; + rfl::Rename<"lastName", LastName> last_name; + std::vector children; +}; + +// Leads to a runtime error, if the field "lastName" is not "Simpson" +// and the field "firstName" is not "Homer", "Marge", "Bart", "Lisa" or "Maggie". +const auto simpson_family_member = rfl::json::read(some_json_string).value(); +``` +## Support for standard containers + +The serialization and deserialization of containers is handled as follows: + +`std::map`, `std::unordered_map`, +maps with any numeric types (integral and floating points) as keys, +and any objects where the `ReflectionType` is either a `std::string` or +a numeric type 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"} +``` + +The same is true for numeric types: + +```cpp +std::map homer; +homer[1] = "Homer"; +homer[2] = "Simpson"; +``` + +This will be represented as follows: + +```json +{"1":"Homer","2":"Simpson"} +``` + +If you wrap your keys into a `rfl::Validator`, this will be treated as an object as well: + +```cpp +using Between1and3 = rfl::Validator, rfl::Maximum<3>>; +std::map homer; +homer[1] = "Homer"; +homer[2] = "Simpson"; +``` + +This will also be represented as follows: + +```json +{"1":"Homer","2":"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. + +## Variants and tagged unions + +### untagged + +Sometimes you know that the JSON object can be one of several alternatives. For example, +you might have several shapes like `Circle`, `Rectangle` or `Square`. For these kind of +cases, the C++ standard library contains `std::variant`, even though we we recommend you to use `rfl::Variant` instead: + +```cpp +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant; + +const Shapes r = Rectangle{.height = 10, .width = 5}; + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +This code will compile just fine and work as intended. However, there are +several problems with this: + +1. It is in inefficient: The parser has to read the fields for all of the different alternatives until it can't find a required field in the JSON object. It will then move on to the next alternative. + +2. It leads to confusing error messages: If none of the alternatives can be matched, you will get an error message telling you why each of the alternatives couldn't be matched. Such error messages are very long-winding and hard to read. + +3. It is dangerous. Imagine we had written `std::variant` instead of `std::variant`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs. + +### internally tagged + +One way to solve this problem is to add a tag inside the class. That is why we have provided a helper class for these purposes: `rfl::TaggedUnion`. + +TaggedUnions use the name of the struct as an identifying tag. It will then try to take that field from the JSON object, match it to the correct alternative and then only parse the correct alternative. + +We will now rewrite the example from above using `rfl::TaggedUnion`: + +```cpp +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +// Now you tell rfl::TaggedUnion that you want it to write the name +// of the struct into an extra field called "shape". +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +const Shapes r = Rectangle{.height = 10, .width = 5}; + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +The resulting JSON looks like this: +```json +{"shape":"Rectangle","height":10.0,"width":5.0} +``` + +Because the tag is inside the JSON object, this is called *internally tagged*. +It is the standard in Python's [pydantic](https://docs.pydantic.dev/latest/api/standard_library_types/#union). + +It is also possible to set the tag explicitly: + +```cpp +struct Circle { + using Tag = rfl::Literal<"circle", "Circle">; + double radius; +}; + +struct Rectangle { + using Tag = rfl::Literal<"rectangle", "Rectangle">; + double height; + double width; +}; + +struct Square { + using Tag = rfl::Literal<"square", "Square">; + double width; +}; + +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +const Shapes r = Rectangle{.height = 10, .width = 5}; + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +The JSON generated by `rfl::json::write` looks like this: + +```json +{"shape":"rectangle","height":10.0,"width":5.0} +``` + +However, `rfl::json::read` would also accept this: + +```json +{"shape":"Rectangle","height":10.0,"width":5.0} +``` + +If the behavior of your program depends on the value the user has decided to pass, then +you can also set the tag as a field explicitly. + +For instance, if it somehow makes a difference +whether the JSON contains "Rectangle" or "rectangle", you can do the following: + +```cpp +struct Circle { + rfl::Literal<"circle", "Circle"> shape; + double radius; +}; + +struct Rectangle { + rfl::Literal<"rectangle", "Rectangle"> shape; + double height; + double width; +}; + +struct Square { + rfl::Literal<"square", "Square"> shape; + double width; +}; + +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +const Shapes r = Rectangle{ + .shape = rfl::Literal<"rectangle", "Rectangle">::make<"Rectangle">(), + .height = 10, + .width = 5}; + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +Note that in this case the type of the field `shape` MUST be `rfl::Literal`. +Also note that this is exactly how tagged unions work in Pydantic. + +### externally tagged + +Another approach is to add external tags. + +You can do that using `rfl::Field`: + +```cpp +using TaggedVariant = rfl::Variant, rfl::Field<"option2", Type2>, ...>; +``` + +The parser can now figure this out and will only try to parse the field that was indicated by the field name. +Duplicate field names will lead to compile-time errors. + +We can rewrite the example from above: + +```cpp +// Circle, Rectangle and Square are the same as above. +using Shapes = rfl::Variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", Square>>; + +const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +The resulting JSON looks like this: +```json +{"rectangle":{"height":10.0,"width":5.0}} +``` + +Because the tag is external, this is called *externally tagged*. It is the standard in Rust's [serde-json](https://serde.rs/enum-representations.html). + + +### The visitor pattern + +In C++, the idiomatic way to handle `std::variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). + +For instance, the externally tagged `rfl::Variant` from the example above could be handled like this: + +```cpp +using Shapes = rfl::Variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", Square>>; + +const Shapes my_shape = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + +const auto handle_shapes = [](const auto& field) { + using Name = typename std::decay_t(decltype(field))::Name; + if constexpr (std::is_same>()) { + std::cout << is circle, radius: << field.value().radius() << std::endl; + } else if constexpr (std::is_same>()) { + std::cout << is rectangle, width: << field.value().width() << ", height: " << field.value().height() << std::endl; + } else if constexpr (std::is_same>()) { + std::cout << is square, width: << field.value().width() << std::endl; + } else { + // reflect-cpp also provides this very useful helper that ensures + // at compile-time that you didn't forget anything. + static_assert(rfl::always_false_v, "Not all cases were covered."); + } +}; + +std::visit(handle_shapes, my_shape.variant()); +``` + +Likewise, `rfl::TaggedUnion` contains `std::variant` under-the-hood. The original variant can be +retrieved using `.variant()`: + +```cpp +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +const Shapes my_shape = Rectangle{.height = 10, .width = 5}; + +const auto handle_shapes = [](const auto& s) { + using Type = std::decay_t(decltype(s)); + if constexpr (std::is_same()) { + std::cout << is circle, radius: << s.radius() << std::endl; + } else if constexpr (std::is_same()) { + std::cout << is rectangle, width: << s.width() << ", height: " << s.height() << std::endl; + } else if constexpr (std::is_same()) { + std::cout << is square, width: << s.width() << std::endl; + } else { + static_assert(rfl::always_false_v, "Not all cases were covered."); + } +}; + +std::visit(handle_shapes, my_shape.variant()); +``` + + + + + +## Timestamp + +`rfl::Timestamp` is a simple wrapper around `std::tm` (https://en.cppreference.com/w/cpp/chrono/c/tm). + +As its template parameter it includes the time stamp format for serialization and deserialization. + +Here is a reference for for how you can specify the format: + +https://en.cppreference.com/w/cpp/chrono/c/strftime + +In fact, `rfl::Timestamp` calls `strftime` and `strptime` under-the-hood. + +They can be used in your struct like this: + +```cpp +struct Person { + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; +}; +``` + +An `rfl::Timestamp` can be constructed from either a string or a `std::tm` struct. + +```cpp +const auto person1 = Person{.birthday = "1970-01-01"}; +const auto person2 = Person{.birthday = std::tm{...}}; +``` + +You can access the underlying `std::tm` struct using the `.tm()` method and you can generate +the string representation using the `.str()` method. + +```cpp +const std::tm birthday = person1.birthday().tm(); +std::cout << person1.birthday().str() << std::endl; +``` + +Note that constructing `rfl::Timestamp` from a string is convenient, but it might result in +an exception. + +To avoid the exception you can also use `Timestamp<...>::from_string(...)`, which will +return an `rfl::Result>` or `rfl::Error`. + +```cpp +const rfl::Result> result = rfl::Timestamp<"%Y-%m-%d">::from_string("1970-01-01"); +const rfl::Result> error = rfl::Timestamp<"%Y-%m-%d">::from_string("not a proper time format"); +``` diff --git a/docs/concepts/validators.md b/docs/concepts/validators.md new file mode 100644 index 00000000..53f38cdd --- /dev/null +++ b/docs/concepts/validators.md @@ -0,0 +1,119 @@ + +## Validating numbers + +reflect-cpp can also be used to impose condition on numbers. For instance, +if you want an integer that is greater or equal to 10, you can do the following: + +```cpp +using IntGreaterThan10 = rfl::Validator>; +``` + +When you then use the type `IntGreaterThan10` inside you `rfl::Field`, the condition will be automatically +validated. + +The underlying value can be retrieved using the `.value()` method. + +The current conditions are currently supported by reflect-cpp: + +- `rfl::EqualTo` +- `rfl::NotEqualTo` +- `rfl::Minimum` +- `rfl::ExclusiveMinimum` +- `rfl::Maximum` +- `rfl::ExclusiveMaximum` + +## Pattern matching + +`rfl::Pattern` can be used to verify that a string fits a particular pattern, the latter of which is expressed as a regular expression. + +A common problem for backend applications or data pipelines is SQL injection. `rfl::Pattern` can be used to limit the allowed characters +users are able to pass. For instance, for table names, we might only allow uppercase characters and +underscores: + +```cpp +using TableName = rfl::Pattern; +``` + +Because the regex is encoded at compile time, you can be certain that whenever you use the type `TableName`, the string contained +therein will fit the pattern. This is a very strong safeguard against SQL injection. + +Note that use also have to give a reasonable name to the pattern. That is, because reflect-cpp emphasizes readable error messages and regex patterns can be somewhat hard to decipher at times. + +To retrieve the underlying string, you can use the `.value()` method. + +reflect-cpp currently contains the following predefined regex patterns: + +- `rfl::AlphaNumeric` +- `rfl::Base64Encoded` +- `rfl::Email` +- `rfl::UUIDv1` +- `rfl::UUIDv2` +- `rfl::UUIDv3` +- `rfl::UUIDv4` + +## Composing validators + +Sometimes the conditions you want to impose are more complex than a simple minimum or a simple regex pattern. That is why reflect-cpp allows you to compose them using the operators `rfl::AnyOf`, `rfl::AllOf` and `rfl::OneOf`. + +- `rfl::AnyOf` requires that *at least one* of the conditions contained therein be true. It thus works like an OR operator. +- `rfl::AllOf` requires that *all* of the conditions contained therein be true. It thus works like an AND operator. +- `rfl::OneOf` requires that *exactly one* of the conditions contained therein be true. It thus works like a XOR operator. + +For instance, if you want to ensure that a person's age is a reasonable number, you can impose two conditions as follows: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + Age age; +}; +``` + +However, if you pass more than one constraint to `rfl::Validator`, they will be automatically connected using `rfl::AllOf`, +so you might as well write: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>; + +... +``` + +You can also nest composed validators. For instance, in this case the age must either be 0-10 or 40-130. + +```cpp +using Age = rfl::Validator< + int, + rfl::AnyOf, rfl::Maximum<10>>, + rfl::AllOf, rfl::Maximum<130>>>>; +``` + +You can also compose regex patterns: + +```cpp +using TableOrColumnName = rfl::Validator< + std::string, + rfl::AnyOf, + rfl::PatternValidator>>; +``` +# `rfl::Size` + +`rfl::Size` can be used to impose constraints on any container that contains the method `.size()`, which includes `std::string`. + +For instance, you can a require a vector to be non-empty as follows: + +```cpp +using NonEmptyStringVector = + rfl::Validator, rfl::Size>>; +``` + +Or you could require it to contain exactly zero or three elements, using validator composition: + +```cpp +using NoneOrThree = + rfl::Validator, + rfl::Size, rfl::EqualTo<3>>>>; +``` + diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 00000000..340019a1 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,66 @@ +## How to contribute +### Compiling and running the tests + +reflect-cpp uses vcpkg for dependency management, including +gtest, which is required for the tests. + +```bash +# bootstrap vcpkg if you haven't done so already +git submodule update --init +./vcpkg/bootstrap-vcpkg.sh # Linux, macOS +./vcpkg/bootstrap-vcpkg.bat # Windows +# You may be prompted to install additional dependencies. +``` + +#### JSON only + +To compile the tests, do the following: + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON +cmake --build build -j 4 # gcc, clang +cmake --build build --config Release -j 4 # MSVC +``` + +To run the tests, do the following: + +``` +./build/tests/json/reflect-cpp-json-tests +``` + +#### All serialization formats + +To compile the tests with serialization formats other than JSON, do the following: + +```bash +cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release +cmake --build build -j 4 # gcc, clang +cmake --build build --config Release -j 4 # MSVC +``` + +To run the tests, do the following: + +``` +./build/tests/bson/reflect-cpp-bson-tests +./build/tests/cbor/reflect-cpp-cbor-tests +./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests +./build/tests/msgpack/reflect-cpp-msgpack-tests +./build/tests/json/reflect-cpp-json-tests +./build/tests/toml/reflect-cpp-toml-tests +./build/tests/xml/reflect-cpp-xml-tests +./build/tests/yaml/reflect-cpp-yaml-tests +``` + +### Make sure includes are relative + +In order for the library to be able to function header-only, we need internal includes to be relative and not depend on any externally set include directory. + +That is, for example, if you are within any file in `rfl/internal`, prefer +```cpp +#include "to_ptr_named_tuple.hpp" +``` +over +```cpp +#include "rfl/internal/to_ptr_named_tuple.hpp" +``` +For further details and reasoning, please refer to [#30](https://github.com/getml/reflect-cpp/issues/30). diff --git a/docs/error_messages.md b/docs/error_messages.md new file mode 100644 index 00000000..859a3371 --- /dev/null +++ b/docs/error_messages.md @@ -0,0 +1,21 @@ +# Error messages + +reflect-cpp returns clear and comprehensive error messages: + +```cpp +const std::string faulty_json_string = + R"({"firstName":"Homer","lastName":12345,"town":"Springfield","birthday":"04/19/1987","age":145,"email":"homer(at)simpson.com"})"; +const auto result = rfl::json::read(faulty_json_string); +``` + +Yields the following error message: + +``` +Found 5 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) Failed to parse field 'age': Value expected to be less than or equal to 130, but got 145. +4) Failed to parse field 'email': String 'homer(at)simpson.com' did not match format 'Email': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'. +5) Field named 'children' not found. +``` + diff --git a/docs/errors/result.md b/docs/errors/result.md new file mode 100644 index 00000000..c4e7403e --- /dev/null +++ b/docs/errors/result.md @@ -0,0 +1,159 @@ +# `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. This is needed for two reasons: + +1) 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. + +2) In some cases, you want to signal to the parser that is fine if some things go wrong. `rfl::Result` is the way to do that. + +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. + +## Using `rfl::Result` for parsing + +Suppose you have a vector with 1000 user-supplied configurations: + +```cpp +const auto configs = rfl::json::read>(json_string); +``` + +Chances are that the user of your software has made as mistake in at least some of these configurations. If you set it up as shown above, `rfl::json::read` will fail if one or more `Config` items contain an error. But sometimes you don't want that. Sometimes you want your software to proceed with the remaining 999 configurations and gently point out to the user that some of the configurations were faulty. + +The solution is to this instead: + +```cpp +const auto configs = rfl::json::read>>(json_string); +``` + +This means `rfl::json::read` is going to cut the end-users of your software some slack. But it also means that you, as the programmer, have to handle the fact that some of the configs might contain errors. + +Below, we will show you how to do that. + +## 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. + +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/errors/validation_errors.md b/docs/errors/validation_errors.md new file mode 100644 index 00000000..859a3371 --- /dev/null +++ b/docs/errors/validation_errors.md @@ -0,0 +1,21 @@ +# Error messages + +reflect-cpp returns clear and comprehensive error messages: + +```cpp +const std::string faulty_json_string = + R"({"firstName":"Homer","lastName":12345,"town":"Springfield","birthday":"04/19/1987","age":145,"email":"homer(at)simpson.com"})"; +const auto result = rfl::json::read(faulty_json_string); +``` + +Yields the following error message: + +``` +Found 5 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) Failed to parse field 'age': Value expected to be less than or equal to 130, but got 145. +4) Failed to parse field 'email': String 'homer(at)simpson.com' did not match format 'Email': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'. +5) Field named 'children' not found. +``` + diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..088b150e --- /dev/null +++ b/docs/index.md @@ -0,0 +1,215 @@ +# ![C++](https://img.shields.io/badge/c++-%2300599C.svg?style=for-the-badge&logo=c%2B%2B&logoColor=white) reflect-cpp + +[![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-11+-blue.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/clang-16+-blue.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/MSVC-17+-blue.svg)](https://shields.io/) + +![image](banner2.png) + + +**reflect-cpp** is a C++-20 library for **fast serialization, deserialization and validation** using reflection, similar to [pydantic](https://github.com/pydantic/pydantic) in Python, [serde](https://github.com/serde-rs) in Rust, [encoding](https://github.com/golang/go/tree/master/src/encoding) in Go or [aeson](https://github.com/haskell/aeson/tree/master) in Haskell. + +As the aforementioned libraries are among the most widely used in the respective languages, reflect-cpp fills an important gap in C++ development. It reduces boilerplate code and increases code safety. + +## Why use reflect-cpp? +- Close integration with containers from the C++ standard library +- Close adherence to C++ idioms +- 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 + +## Serialization formats + +reflect-cpp provides a unified reflection-based interface across different serialization formats. It is deliberately designed in a very modular way, using [concepts](https://en.cppreference.com/w/cpp/language/constraints), to make it as easy as possible to interface various C or C++ libraries related to serialization. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details. + +The following table lists the serialization formats currently supported by reflect-cpp and the underlying libraries used: + +| Format | Library | Version | License | Remarks | +|--------------|------------------------------------------------------|--------------|------------| -----------------------------------------------------| +| JSON | [yyjson](https://github.com/ibireme/yyjson) | >= 0.8.0 | MIT | out-of-the-box support, included in this repository | +| BSON | [libbson](https://github.com/mongodb/libbson) | >= 1.25.1 | Apache 2.0 | JSON-like binary format | +| CBOR | [tinycbor](https://github.com/intel/tinycbor) | >= 0.6.0 | MIT | JSON-like binary format | +| flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26 | Apache 2.0 | Schema-less version of flatbuffers, binary format | +| msgpack | [msgpack-c](https://github.com/msgpack/msgpack-c) | >= 6.0.0 | BSL 1.0 | JSON-like binary format | +| TOML | [toml++](https://github.com/marzer/tomlplusplus) | >= 3.4.0 | MIT | Textual format with an emphasis on readability | +| XML | [pugixml](https://github.com/zeux/pugixml) | >= 1.14 | MIT | Textual format used in many legacy projects | +| YAML | [yaml-cpp](https://github.com/jbeder/yaml-cpp) | >= 0.8.0 | MIT | Textual format with an emphasis on readability | + +Support for more serialization formats is in development. Refer to the [issues](https://github.com/getml/reflect-cpp/issues) for details. + +Please also refer to the *vcpkg.json* in this repository. + +## Simple Example + +```cpp +#include +#include + +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .age = 45}; + +// We can now write into and read from a JSON string. +const std::string json_string = rfl::json::write(homer); +auto homer2 = rfl::json::read(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"first_name":"Homer","last_name":"Simpson","age":45} +``` + +You can transform the field names from `snake_case` to `camelCase` like this: + +```cpp +const std::string json_string = + rfl::json::write(homer); +auto homer2 = + rfl::json::read(json_string).value(); +``` + +The resulting JSON string looks like this: + +```json +{"firstName":"Homer","lastName":"Simpson","age":45} +``` + +Or you can use another format, such as YAML. + +```cpp +#include + +// ... (same as above) + +const std::string yaml_string = rfl::yaml::write(homer); +auto homer2 = rfl::yaml::read(yaml_string).value(); +``` + +The resulting YAML string looks like this: + +```yaml +first_name: Homer +last_name: Simpson +age: 45 +``` + +This will work for just about any example in the entire documentation +and any supported format, except where explicitly noted otherwise: + +```cpp +rfl::bson::write(homer); +rfl::cbor::write(homer); +rfl::flexbuf::write(homer); +rfl::msgpack::write(homer); +rfl::toml::write(homer); +rfl::xml::write(homer); + +rfl::bson::read(bson_bytes); +rfl::cbor::read(cbor_bytes); +rfl::flexbuf::read(flexbuf_bytes); +rfl::msgpack::read(msgpack_bytes); +rfl::toml::read(toml_string); +rfl::xml::read(xml_string); +``` + +## More Comprehensive Example + +```cpp +#include +#include +#include + +// Age must be a plausible number, between 0 and 130. This will +// be validated automatically. +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector children; +}; + +const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + +const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + +const auto homer = + Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .children = std::vector({bart, lisa, maggie})}; + +// We can now transform this into a JSON string. +const std::string json_string = rfl::json::write(homer); +std::cout << json_string << std::endl; + +// We can also directly write into std::cout (or any other std::ostream). +rfl::json::write(homer, std::cout) << std::endl; +``` + +This results in the following JSON string: + +```json +{"firstName":"Homer","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":45,"email":"homer@simpson.com","children":[{"firstName":"Bart","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":10,"email":"bart@simpson.com","children":[]},{"firstName":"Lisa","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":8,"email":"lisa@simpson.com","children":[]},{"firstName":"Maggie","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":0,"email":"maggie@simpson.com","children":[]}]} +``` + +We can also create structs from the string: + +```cpp +auto homer2 = rfl::json::read(json_string).value(); + +// Fields can be accessed like this: +std::cout << "Hello, my name is " << homer.first_name() << " " + << homer.last_name() << "." << std::endl; + +// Since homer2 is mutable, we can also change the values like this: +homer2.first_name = "Marge"; + +std::cout << "Hello, my name is " << homer2.first_name() << " " + << homer2.last_name() << "." << std::endl; +``` + + +## Related projects + +reflect-cpp was originally developed for [getml-community](https://github.com/getml/getml-community), the fastest open-source tool for feature engineering on relational data and time series. If you are interested in Data Science and/or Machine Learning, please check it out. + +## Authors + +reflect-cpp has been developed by [scaleML](https://www.scaleml.de), a company specializing in software engineering and machine learning for enterprise applications. It is extensively used for [getML](https://getml.com), a software for automated feature engineering using relational learning. + +## License + +reflect-cpp is released under the MIT License. Refer to the LICENSE file for details. + +reflect-cpp includes [YYJSON](https://github.com/ibireme/yyjson), the fastest JSON library currently in existence. YYJSON is written by YaoYuan and also released under the MIT License. + +reflect-cpp includes [compile-time-regular-expressions](https://github.com/hanickadot/compile-time-regular-expressions). CTRE is written by Hana Dusíková and released under the Apache-2.0 License with LLVM exceptions. diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 00000000..e4d22ed3 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,68 @@ + +## Installation Options + +The following compilers are supported: + +- GCC 11.4 or higher +- Clang 16.0 or higher +- MSVC 17.8 (19.38) or higher + +### 1. Header-only + +If you **do not** need JSON support or you want to link YYJSON yourself, 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. + +### 2. Include source files into your own build + +Simply copy the contents of the folder `include` into your source repository or add it to your include path and also add `src/yyjson.c` to your source files for compilation. + +If you need support for other serialization formats like flexbuffers or XML, you should also include and link the respective libraries, as listed in the section on serialization formats. + +### 3. Compilation using cmake + +This will simply compile YYJSON, which is the JSON library underlying reflect-cpp. You can then include reflect-cpp in your project and link to the binary +to get reflect-cpp with JSON support. + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j 4 # gcc, clang +cmake --build build --config Release -j 4 # MSVC +``` + +### 4. Compilation using cmake and vcpkg + +If you want serialization formats other than JSON, you can either install them manually or use vcpkg. + +To install vcpkg: + +```bash +git submodule update --init +./vcpkg/bootstrap-vcpkg.sh # Linux, macOS +./vcpkg/bootstrap-vcpkg.bat # Windows +# You may be prompted to install additional dependencies. +``` + +To use reflect-cpp in your project: + +```cmake +add_subdirectory(reflect-cpp) # Add this project as a subdirectory + +set(REFLECTCPP_BSON ON) # Optional +set(REFLECTCPP_CBOR ON) # Optional +set(REFLECTCPP_FLEXBUFFERS ON) # Optional +set(REFLECTCPP_MSGPACK ON) # Optional +set(REFLECTCPP_TOML ON) # Optional +set(REFLECTCPP_XML ON) # Optional +set(REFLECTCPP_YAML ON) # Optional + +target_link_libraries(your_project PRIVATE reflectcpp) # Link against the library +``` + +##### Troubleshooting vcpkg + +vcpkg is a great, but very ambitious and complex project (just like C++ is a great, but very ambitious and complex language). Here are some of the you might run into and how to resolve them: + +1. A lot of problems can simply be resolved by deleting the build directory using `rm -rf build`. + +2. *Environment variable VCPKG_FORCE_SYSTEM_BINARIES must be set on arm, s390x, ppc64le and riscv platforms.* - This usually happens on arm platforms like the Apple Silicon chips and can be resolved by simply preceding your build with `export VCPKG_FORCE_SYSTEM_BINARIES=arm` or `export VCPKG_FORCE_SYSTEM_BINARIES=1`. + +3. On some occasions you might be asked to specify a compiler. You can do so by simply adding it to the cmake command as follows: `cmake -S . -B build ... -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++` or `cmake -S . -B build ... -DCMAKE_C_COMPILER=clang-17 -DCMAKE_CXX_COMPILER=clang++-17` (or whatever supported compiler you would like to use). diff --git a/docs/reflective_programming.md b/docs/reflective_programming.md new file mode 100644 index 00000000..28172017 --- /dev/null +++ b/docs/reflective_programming.md @@ -0,0 +1,98 @@ +## Reflective programming + +Beyond serialization and deserialization, reflect-cpp also supports reflective programming in general. + +For instance: + +```cpp +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::string town = "Springfield"; + unsigned int age; + std::vector children; +}; + +for (const auto& f : rfl::fields()) { + std::cout << "name: " << f.name() << ", type: " << f.type() << std::endl; +} +``` + +You can also create a view and then access these fields using `std::get` or `rfl::get`, or iterate over the fields at compile-time: + +```cpp +auto lisa = Person{.first_name = "Lisa", .last_name = "Simpson", .age = 8}; + +const auto view = rfl::to_view(lisa); + +// view.values() is a std::tuple containing +// pointers to the original fields. +// This will modify the struct `lisa`: +*std::get<0>(view.values()) = "Maggie"; + +// All of this is supported as well: +*view.get<1>() = "Simpson"; +*view.get<"age">() = 0; +*rfl::get<0>(view) = "Maggie"; +*rfl::get<"first_name">(view) = "Maggie"; + +view.apply([](const auto& f) { + // f is a an rfl::Field pointing to the original field. + std::cout << f.name() << ": " << rfl::json::write(*f.value()) << std::endl; +}); +``` + +It also possible to replace fields: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + std::vector children; +}; + +const auto lisa = Person{.first_name = "Lisa", .last_name = "Simpson"}; + +// Returns a deep copy of "lisa" with the first_name replaced. +const auto maggie = rfl::replace( + lisa, rfl::make_field<"first_name">(std::string("Maggie"))); +``` + +Or you can create structs from other structs: + +```cpp +struct A { + std::string f1; + std::string f2; +}; + +struct B { + std::string f3; + std::string f4; +}; + +struct C { + std::string f1; + std::string f2; + std::string f4; +}; + +const auto a = A{.f1 = "Hello", .f2 = "World"}; + +const auto b = B{.f3 = "Hello", .f4 = "World"}; + +// f1 and f2 are taken from a, f4 is taken from b, f3 is ignored. +const auto c = rfl::as(a, b); +``` + +You can also replace fields in structs using fields from other structs: + +```cpp +const auto a = A{.f1 = "Hello", .f2 = "World"}; + +const auto c = C{.f1 = "C++", .f2 = "is", .f4 = "great"}; + +// The fields f1 and f2 are replaced with the fields f1 and f2 in a. +const auto c2 = rfl::replace(c, a); +``` + diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 00000000..b1ffe394 --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,7 @@ +:root { + --md-primary-fg-color: #42A5B9; + --md-primary-fg-color--light: #42A5B9; + --md-primary-fg-color--dark: #7A6A6E; + --md-accent-fg-color: #F0685C; + --md-accent-fg-color--transparent: #F0685C; +} diff --git a/docs/validation_errors.md b/docs/validation_errors.md new file mode 100644 index 00000000..859a3371 --- /dev/null +++ b/docs/validation_errors.md @@ -0,0 +1,21 @@ +# Error messages + +reflect-cpp returns clear and comprehensive error messages: + +```cpp +const std::string faulty_json_string = + R"({"firstName":"Homer","lastName":12345,"town":"Springfield","birthday":"04/19/1987","age":145,"email":"homer(at)simpson.com"})"; +const auto result = rfl::json::read(faulty_json_string); +``` + +Yields the following error message: + +``` +Found 5 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) Failed to parse field 'age': Value expected to be less than or equal to 130, but got 145. +4) Failed to parse field 'email': String 'homer(at)simpson.com' did not match format 'Email': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'. +5) Field named 'children' not found. +``` + diff --git a/docs/welcome.md b/docs/welcome.md new file mode 100644 index 00000000..e69de29b diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..f04fe064 --- /dev/null +++ b/flake.nix @@ -0,0 +1,46 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11"; + devenv.url = "github:cachix/devenv"; + nixpkgs-python.url = "github:cachix/nixpkgs-python"; + nixpkgs-python.inputs = { nixpkgs.follows = "nixpkgs"; }; + }; + + nixConfig = { + extra-trusted-public-keys = "devenv.cachix.org-1:w1cLUi8dv3hnoSPGAuibQv+f9TZLr6cv/Hm9XgU50cw="; + extra-substituters = "https://devenv.cachix.org"; + }; + + outputs = { self, nixpkgs, devenv, getml_flake, ... } @ inputs: + let + system = "x86_64-linux"; + #pkgs = nixpkgs.legacyPackages.${system}; + in + { + packages.${system}.devenv-up = self.devShells.${system}.default.config.procfileScript; + + devShells.${system}.default = devenv.lib.mkShell { + inherit inputs pkgs; + modules = [ + ({ pkgs, config, ... }: { + # This is your devenv configuration + languages.python = { + enable = true; + version = "3.11.3"; + + venv.enable = true; + venv.requirements = '' + mkdocs mkdocs-material mkdocsstrings + ''; + }; + + #enterShell = '' + # export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath [pkgs.zlib]}:$LD_LIBRARY_PATH + # export LD_LIBRARY_PATH=${pkgs.stdenv.cc.cc.lib}/lib:$LD_LIBRARY_PATH + #''; + + }) + ]; + }; + }; +}