number_constraint.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include <cmath>
  3. #include <limits>
  4. #include <jvalidate/detail/number.h>
  5. #include <jvalidate/forward.h>
  6. namespace jvalidate::constraint {
  7. /**
  8. * @brief A constraint on the Int and Double types, asserting that the given
  9. * arg is less than the stored value. Equality is accepted or rejected based
  10. * on exclusive being true or not.
  11. * Unlike other constraint types, numeric constraints are trivial and thus
  12. * are implemented directly in the constraint object.
  13. *
  14. * https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.2
  15. * https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.3
  16. */
  17. struct MaximumConstraint {
  18. double value = 0;
  19. bool exclusive = false;
  20. bool operator()(double arg) const { return exclusive ? arg < value : arg <= value; }
  21. };
  22. /**
  23. * @brief A constraint on the Int and Double types, asserting that the given
  24. * arg is greater than the stored value. Equality is accepted or rejected based
  25. * on exclusive being true or not.
  26. * Unlike other constraint types, numeric constraints are trivial and thus
  27. * are implemented directly in the constraint object.
  28. *
  29. * https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.4
  30. * https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.5
  31. */
  32. struct MinimumConstraint {
  33. double value = 0;
  34. bool exclusive = false;
  35. bool operator()(double arg) const { return exclusive ? arg > value : arg >= value; }
  36. };
  37. /**
  38. * @brief A constraint on the Int and Double types, asserting that the given
  39. * arg is a multiple of the stored value.
  40. * Unlike other constraint types, numeric constraints are trivial and thus
  41. * are implemented directly in the constraint object.
  42. *
  43. * https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2.1
  44. */
  45. struct MultipleOfConstraint {
  46. double value = 1;
  47. bool operator()(double arg) const {
  48. if (std::fabs(std::remainder(arg, value)) <= std::numeric_limits<double>::epsilon()) {
  49. return true;
  50. }
  51. double const div = arg / value;
  52. return std::isfinite(div) && detail::is_json_integer(div);
  53. }
  54. };
  55. }