Use ctre::match in rfl/PatternValidator.hpp instead of std::regex

This commit is contained in:
Txema Ynzenga
2023-12-28 13:46:36 +01:00
parent b2f515d0e5
commit f89913f1a3
3 changed files with 7 additions and 38 deletions
+5 -37
View File
@@ -1,16 +1,10 @@
#ifndef RFL_PATTERNVALIDATOR_HPP_
#define RFL_PATTERNVALIDATOR_HPP_
#include <ctime>
#include <iterator>
#include <optional>
#include <regex>
#include <stdexcept>
#include <string>
#include "rfl/Literal.hpp"
#include "../ctre.hpp"
#include "rfl/Result.hpp"
#include "rfl/internal/Memoization.hpp"
#include "rfl/internal/StringLiteral.hpp"
namespace rfl {
@@ -18,38 +12,12 @@ namespace rfl {
template <internal::StringLiteral _regex, internal::StringLiteral _name>
struct PatternValidator {
static Result<std::string> validate(const std::string& _str) noexcept {
const auto check_pattern =
[&](const auto _regex_pattern) -> rfl::Result<std::string> {
if (!std::regex_match(_str, *_regex_pattern)) {
return rfl::Error("String '" + _str + "' did not match format '" +
_name.str() + "': '" + _regex.str() + "'.");
}
if (ctre::match<_regex.arr_>(_str))
return _str;
};
return regex_pattern().and_then(check_pattern);
else
return rfl::Error("String '" + _str + "' did not match format '" +
_name.str() + "': '" + _regex.str() + "'.");
}
private:
/// Uses a memoization pattern to init the pattern.
static rfl::Result<const std::regex*> regex_pattern() noexcept {
const auto compile_pattern = [](std::optional<std::regex>* _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<std::optional<std::regex>> regex_pattern_;
};
} // namespace rfl
+1
View File
@@ -11,6 +11,7 @@
#include "rfl/internal/is_basic_type.hpp"
#include "rfl/internal/strings/replace_all.hpp"
#include "rfl/parsing/is_required.hpp"
#include "../internal/Memoization.hpp"
namespace rfl {
namespace parsing {
+1 -1
View File
@@ -15,7 +15,7 @@ using Base64Encoded = Pattern<R"(^[A-Za-z0-9+/]*(={0,2})?$)", "Base64Encoded">;
/// This pattern will match email addresses.
using Email =
Pattern<R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)", "Email">;
Pattern<R"(^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$)", "Email">;
using UUIDv1 = Pattern<
R"(^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-1[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$)",