#ifndef RFL_PATTERNVALIDATOR_HPP_ #define RFL_PATTERNVALIDATOR_HPP_ #include #include #include #include #include #include #include "rfl/Literal.hpp" #include "rfl/Result.hpp" #include "rfl/internal/Memoization.hpp" #include "rfl/internal/StringLiteral.hpp" namespace rfl { template struct PatternValidator { static Result validate(const std::string& _str) noexcept { const auto check_pattern = [&](const auto _regex_pattern) -> rfl::Result { if (!std::regex_match(_str, *_regex_pattern)) { return rfl::Error("String '" + _str + "' did not match format '" + _name.str() + "': '" + _regex.str() + "'."); } return _str; }; return regex_pattern().and_then(check_pattern); } private: /// Uses a memoization pattern to init the pattern. static rfl::Result regex_pattern() noexcept { const auto compile_pattern = [](std::optional* _regex_pattern) { try { *_regex_pattern = std::regex(_regex.str()); } catch (std::exception& e) { return; } }; const auto& r = regex_pattern_.value(compile_pattern); if (!r) { return Error("Regex pattern '" + _regex.str() + "' failed to compile."); } return &(*r); } private: /// The underlying regex pattern. static inline internal::Memoization> regex_pattern_; }; } // namespace rfl #endif