MCPcopy Create free account
hub / github.com/pboettch/json-schema-validator / numeric

Class numeric

src/json-validator.cpp:885–976  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

883
884template <typename T>
885class numeric : public schema
886{
887 std::pair<bool, T> maximum_{false, 0};
888 std::pair<bool, T> minimum_{false, 0};
889
890 bool exclusiveMaximum_ = false;
891 bool exclusiveMinimum_ = false;
892
893 std::pair<bool, json::number_float_t> multipleOf_{false, 0};
894
895 // multipleOf - if the remainder of the division is 0 -> OK
896 bool violates_multiple_of(T x) const
897 {
898 double res = std::remainder(x, multipleOf_.second);
899 double multiple = std::fabs(x / multipleOf_.second);
900 if (multiple > 1) {
901 res = res / multiple;
902 }
903 double eps = std::nextafter(x, 0) - static_cast<double>(x);
904
905 return std::fabs(res) > std::fabs(eps);
906 }
907
908 void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override
909 {
910 T value = instance; // conversion of json to value_type
911
912 std::ostringstream oss;
913
914 if (multipleOf_.first && value != 0) // zero is multiple of everything
915 if (violates_multiple_of(value))
916 oss << "instance is not a multiple of " << json(multipleOf_.second);
917
918 if (maximum_.first) {
919 if (exclusiveMaximum_ && value >= maximum_.second)
920 oss << "instance exceeds or equals maximum of " << json(maximum_.second);
921 else if (value > maximum_.second)
922 oss << "instance exceeds maximum of " << json(maximum_.second);
923 }
924
925 if (minimum_.first) {
926 if (exclusiveMinimum_ && value <= minimum_.second)
927 oss << "instance is below or equals minimum of " << json(minimum_.second);
928 else if (value < minimum_.second)
929 oss << "instance is below minimum of " << json(minimum_.second);
930 }
931
932 oss.seekp(0, std::ios::end);
933 auto size = oss.tellp();
934 if (size != 0) {
935 oss.seekp(0, std::ios::beg);
936 e.error(ptr, instance, oss.str());
937 }
938 }
939
940public:
941 numeric(const json &sch, root_schema *root, std::set<std::string> &kw)
942 : schema(root)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected