validator.h 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. bool search(std::string const & regex, std::string const & text) {
  27. auto const & re = cache_.try_emplace(regex, regex).first->second;
  28. return std::regex_search(text, re);
  29. }
  30. };
  31. /**
  32. * @brief An implementation of an "Extension Constraint Visitor" plugin that
  33. * does nothing.
  34. */
  35. struct StubExtensionVisitor {};
  36. }
  37. namespace jvalidate {
  38. /**
  39. * @brief A validator is the tool by which a JSON object is actually validated
  40. * against a schema.
  41. *
  42. * @tparam RE A type that can be used to solve regular expressions
  43. */
  44. template <RegexEngine RE = detail::StdRegexEngine,
  45. typename ExtensionVisitor = detail::StubExtensionVisitor>
  46. class Validator {
  47. private:
  48. schema::Node const & schema_;
  49. ValidationConfig cfg_;
  50. ExtensionVisitor extension_;
  51. RE regex_;
  52. public:
  53. /**
  54. * @brief Construct a Validator
  55. *
  56. * @param schema The root schema being validated against. Must outlive this.
  57. *
  58. * @param cfg Any special (runtime) configuration rules being applied to the
  59. * validator.
  60. */
  61. Validator(schema::Node const & schema, ExtensionVisitor extension = {},
  62. ValidationConfig const & cfg = {})
  63. : schema_(schema), cfg_(cfg), extension_(extension) {}
  64. Validator(schema::Node const & schema, ValidationConfig const & cfg)
  65. : schema_(schema), cfg_(cfg) {}
  66. template <typename... Args> Validator(schema::Node &&, Args &&...) = delete;
  67. /**
  68. * @brief Run validation on the given JSON
  69. *
  70. * @tparam A Any Adapter type, in principle a subclass of adapter::Adapter.
  71. * Disallows mutation via ValidationConfig.construct_default_values
  72. *
  73. * @param json The value being validated
  74. *
  75. * @param result An optional out-param of detailed information about
  76. * validation failures. If result is not provided, then the validator will
  77. * terminate on the first error. Otherwise it will run through the entire
  78. * schema to provide a record of all of the failures.
  79. */
  80. template <Adapter A>
  81. requires(not MutableAdapter<A>)
  82. bool validate(A const & json, ValidationResult * result = nullptr) {
  83. EXPECT_M(not cfg_.construct_default_values,
  84. "Cannot perform mutations on an immutable JSON Adapter");
  85. return static_cast<bool>(
  86. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  87. }
  88. /**
  89. * @brief Run validation on the given JSON
  90. *
  91. * @tparam A Any Adapter type that supports assignment, in principle a
  92. * subclass of adapter::Adapter.
  93. *
  94. * @param json The value being validated. Because A is a reference-wrapper,
  95. * the underlying value may be mutated.
  96. *
  97. * @param result An optional out-param of detailed information about
  98. * validation failures. If result is not provided, then the validator will
  99. * terminate on the first error. Otherwise it will run through the entire
  100. * schema to provide a record of all of the failures.
  101. */
  102. template <MutableAdapter A> bool validate(A const & json, ValidationResult * result = nullptr) {
  103. return static_cast<bool>(
  104. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  105. }
  106. /**
  107. * @brief Run validation on the given JSON
  108. *
  109. * @tparam JSON A concrete JSON type. Will be turned into an Adapter, or a
  110. * MutableAdapter (if json is non-const and exists).
  111. *
  112. * @param json The value being validated.
  113. *
  114. * @param result An optional out-param of detailed information about
  115. * validation failures. If result is not provided, then the validator will
  116. * terminate on the first error. Otherwise it will run through the entire
  117. * schema to provide a record of all of the failures.
  118. */
  119. template <typename JSON>
  120. requires(not Adapter<JSON>)
  121. bool validate(JSON & json, ValidationResult * result = nullptr) {
  122. return validate(adapter::AdapterFor<JSON>(json), result);
  123. }
  124. };
  125. }