Added OneOf

This commit is contained in:
Patrick Urbanke
2023-11-02 20:02:34 +01:00
parent 70b11650f8
commit ba997272c7
4 changed files with 94 additions and 0 deletions
+1
View File
@@ -9,6 +9,7 @@
#include "rfl/Flatten.hpp"
#include "rfl/Literal.hpp"
#include "rfl/NamedTuple.hpp"
#include "rfl/OneOf.hpp"
#include "rfl/Ref.hpp"
#include "rfl/TaggedUnion.hpp"
#include "rfl/Timestamp.hpp"
+63
View File
@@ -0,0 +1,63 @@
#ifndef RFL_ONEOF_HPP_
#define RFL_ONEOF_HPP_
#include <string>
#include <utility>
#include <vector>
#include "rfl/Result.hpp"
namespace rfl {
/// Requires that all of the contraints C and Cs be true.
template <class C, class... Cs>
struct OneOf {
template <class T>
static rfl::Result<T> validate(const T& _value) noexcept {
return validate_impl<T, C, Cs...>(_value, {});
}
private:
static Error make_error_message(const std::vector<Error>& _errors) {
std::string msg = "Expected exactly 1 out of " +
std::to_string(sizeof...(Cs) + 1) +
" validations to pass, but " +
std::to_string(sizeof...(Cs) + 1 - _errors.size()) +
" of them did. The following errors were generated: ";
for (size_t i = 0; i < _errors.size(); ++i) {
msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what();
}
return Error(msg);
}
template <class T, class Head, class... Tail>
static rfl::Result<T> validate_impl(const T& _value,
std::vector<Error> _errors) {
const auto push_back = [&](Error&& _err) -> rfl::Result<T> {
_errors.emplace_back(std::forward<Error>(_err));
return _err;
};
const auto next_validation = [&](rfl::Result<T>&& _r) -> rfl::Result<T> {
_r.or_else(push_back);
if constexpr (sizeof...(Tail) == 0) {
if (_errors.size() == sizeof...(Cs)) {
return _value;
}
return make_error_message(_errors);
} else {
return validate_impl<T, Tail...>(
_value, std::forward<std::vector<Error>>(_errors));
}
};
return Head::validate(_value)
.and_then(next_validation)
.or_else(next_validation);
}
};
} // namespace rfl
#endif
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_one_of() {
std::cout << "test_one_of" << std::endl;
using Age = rfl::Validator<
unsigned int,
rfl::OneOf<rfl::AllOf<rfl::Minimum<0.>, rfl::Maximum<10.>>,
rfl::AllOf<rfl::Minimum<40.>, rfl::Maximum<130.>>>>;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"age", Age> age;
};
const auto homer =
Person{.first_name = "Homer", .last_name = "Simpson", .age = 45};
write_and_read(homer,
R"({"firstName":"Homer","lastName":"Simpson","age":45})");
}
+2
View File
@@ -34,6 +34,7 @@
#include "test_unique_ptr.hpp"
#include "test_unique_ptr2.hpp"
//#include "test_constr.hpp"
#include "test_one_of.hpp"
#include "test_unordered_map.hpp"
#include "test_unordered_multimap.hpp"
#include "test_unordered_multiset.hpp"
@@ -85,6 +86,7 @@ int main() {
test_all_of();
test_any_of();
test_one_of();
// test_constr();
return 0;