validator.h 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. #pragma once
  2. #include <regex>
  3. #include <unordered_map>
  4. #include <jvalidate/forward.h>
  5. #include <jvalidate/status.h>
  6. #include <jvalidate/validation_config.h>
  7. #include <jvalidate/validation_visitor.h>
  8. namespace jvalidate::detail {
  9. /**
  10. * @brief An implementation of a regular expression "engine", for use with
  11. * constraints like "pattern" and "patternProperties".
  12. * Uses std::regex as its underlying implementation.
  13. *
  14. * While being std::regex means that it is the most sensible choice for a
  15. * default RegexEngine, the performance of std::regex is generally the worst
  16. * among C++ regex utilities, and it struggles to compile several patterns.
  17. * See https://stackoverflow.com/questions/70583395/ for an explaination.
  18. *
  19. * If you need to use complicated patterns in your json schema, provide a
  20. * RegexEngine compatible wrapper for a different library, such as re2.
  21. */
  22. class StdRegexEngine {
  23. private:
  24. std::unordered_map<std::string, std::regex> cache_;
  25. public:
  26. static bool is_regex(std::string_view regex) {
  27. try {
  28. [[maybe_unused]] std::regex _{std::string(regex)};
  29. return true;
  30. } catch (std::exception const &) { return false; }
  31. }
  32. bool search(std::string const & regex, std::string const & text) {
  33. auto const & re = cache_.try_emplace(regex, regex).first->second;
  34. return std::regex_search(text, re);
  35. }
  36. };
  37. /**
  38. * @brief An implementation of an "Extension Constraint Visitor" plugin that
  39. * does nothing.
  40. */
  41. struct StubExtensionVisitor {};
  42. }
  43. namespace jvalidate {
  44. /**
  45. * @brief A validator is the tool by which a JSON object is actually validated
  46. * against a schema.
  47. *
  48. * @tparam RE A type that can be used to solve regular expressions
  49. */
  50. template <RegexEngine RE = detail::StdRegexEngine,
  51. typename ExtensionVisitor = detail::StubExtensionVisitor>
  52. class Validator {
  53. private:
  54. schema::Node const & schema_;
  55. ValidationConfig cfg_;
  56. ExtensionVisitor extension_;
  57. RE regex_;
  58. public:
  59. /**
  60. * @brief Construct a Validator
  61. *
  62. * @param schema The root schema being validated against. Must outlive this.
  63. *
  64. * @param cfg Any special (runtime) configuration rules being applied to the
  65. * validator.
  66. */
  67. Validator(schema::Node const & schema, ExtensionVisitor extension = {},
  68. ValidationConfig const & cfg = {})
  69. : schema_(schema), cfg_(cfg), extension_(extension) {}
  70. Validator(schema::Node const & schema, ValidationConfig const & cfg)
  71. : schema_(schema), cfg_(cfg) {}
  72. template <typename... Args> Validator(schema::Node &&, Args &&...) = delete;
  73. /**
  74. * @brief Run validation on the given JSON
  75. *
  76. * @tparam A Any Adapter type, in principle a subclass of adapter::Adapter.
  77. * Disallows mutation via ValidationConfig.construct_default_values
  78. *
  79. * @param json The value being validated
  80. *
  81. * @param result An optional out-param of detailed information about
  82. * validation failures. If result is not provided, then the validator will
  83. * terminate on the first error. Otherwise it will run through the entire
  84. * schema to provide a record of all of the failures.
  85. */
  86. template <Adapter A>
  87. requires(not MutableAdapter<A>)
  88. bool validate(A const & json, ValidationResult * result = nullptr) {
  89. EXPECT_M(not cfg_.construct_default_values,
  90. "Cannot perform mutations on an immutable JSON Adapter");
  91. return static_cast<bool>(
  92. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  93. }
  94. /**
  95. * @brief Run validation on the given JSON
  96. *
  97. * @tparam A Any Adapter type that supports assignment, in principle a
  98. * subclass of adapter::Adapter.
  99. *
  100. * @param json The value being validated. Because A is a reference-wrapper,
  101. * the underlying value may be mutated.
  102. *
  103. * @param result An optional out-param of detailed information about
  104. * validation failures. If result is not provided, then the validator will
  105. * terminate on the first error. Otherwise it will run through the entire
  106. * schema to provide a record of all of the failures.
  107. */
  108. template <MutableAdapter A> bool validate(A const & json, ValidationResult * result = nullptr) {
  109. return static_cast<bool>(
  110. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  111. }
  112. /**
  113. * @brief Run validation on the given JSON
  114. *
  115. * @tparam JSON A concrete JSON type. Will be turned into an Adapter, or a
  116. * MutableAdapter (if json is non-const and exists).
  117. *
  118. * @param json The value being validated.
  119. *
  120. * @param result An optional out-param of detailed information about
  121. * validation failures. If result is not provided, then the validator will
  122. * terminate on the first error. Otherwise it will run through the entire
  123. * schema to provide a record of all of the failures.
  124. */
  125. template <typename JSON>
  126. requires(not Adapter<JSON>)
  127. bool validate(JSON & json, ValidationResult * result = nullptr) {
  128. return validate(adapter::AdapterFor<JSON>(json), result);
  129. }
  130. };
  131. }