Parcourir la source

refactor: pass regex engine into format validator

Sam Jaffe il y a 3 mois
Parent
commit
b668d68059

+ 3 - 1
include/jvalidate/format.h

@@ -4,6 +4,7 @@
 #include <cstddef>
 #include <ctime>
 #include <string>
+#include <string_view>
 #include <unordered_map>
 #include <utility>
 
@@ -303,7 +304,7 @@ private:
       {"iri-reference", nullptr},
       {"json-pointer", &format::json_pointer},
       {"relative-json-pointer", &format::ctor_as_valid<detail::RelativePointer>},
-      /* {"regex", &detail::StdRegexEngine::is_valid}, */
+      {"regex", nullptr},
       {"time", &format::time},
       {"uri", nullptr},
       {"uri-reference", nullptr},
@@ -313,6 +314,7 @@ private:
 
 public:
   FormatValidator() = default;
+  FormatValidator(Predicate is_regex) { supported_formats_.insert_or_assign("regex", is_regex); }
 
   Status operator()(std::string const & format, std::string_view text) const {
     if (auto it = supported_formats_.find(format); it != supported_formats_.end() && it->second) {

+ 3 - 2
include/jvalidate/forward.h

@@ -163,8 +163,9 @@ concept MutableAdapter = Adapter<A> && requires(A const a) {
 };
 
 template <typename R>
-concept RegexEngine = requires(R & regex) {
-  { regex.search("" /* pattern */, "" /* text */) } -> std::same_as<bool>;
+concept RegexEngine = requires(R & engine) {
+  { R::is_regex("") } -> std::same_as<bool>;
+  { engine.search("" /* pattern */, "" /* text */) } -> std::same_as<bool>;
 };
 
 template <typename E, typename A, typename B, typename V>

+ 1 - 1
include/jvalidate/validation_visitor.h

@@ -282,7 +282,7 @@ public:
       return true;
     }
 
-    switch (FormatValidator()(cons.format, document.as_string())) {
+    switch (FormatValidator(&RE::is_regex)(cons.format, document.as_string())) {
     case FormatValidator::Status::Unimplemented:
       return result(Status::Reject, "unimplemented format '", cons.format, "'");
     case FormatValidator::Status::Invalid:

+ 3 - 3
include/jvalidate/validator.h

@@ -27,11 +27,11 @@ private:
   std::unordered_map<std::string, std::regex> cache_;
 
 public:
-  static bool is_valid(std::string const & regex) {
+  static bool is_regex(std::string_view regex) {
     try {
-      [[maybe_unused]] std::regex _{regex};
+      [[maybe_unused]] std::regex _{std::string(regex)};
       return true;
-    } catch (...) { return false; }
+    } catch (std::exception const &) { return false; }
   }
 
   bool search(std::string const & regex, std::string const & text) {