validator.h 4.3 KB

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