adapter.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #pragma once
  2. #include <cstdint>
  3. #include <optional>
  4. #include <ostream>
  5. #include <jvalidate/detail/array_iterator.h>
  6. #include <jvalidate/detail/number.h>
  7. #include <jvalidate/detail/object_iterator.h>
  8. #include <jvalidate/enum.h>
  9. #include <jvalidate/forward.h>
  10. #include <jvalidate/status.h>
  11. namespace jvalidate::adapter {
  12. /**
  13. * @brief An interface for a type-erased reference-wrapper around a JSON node.
  14. *
  15. * Unlike languages like python, there are dozens of different C++ Libraries
  16. * for JSON parsing/construction. Each of these libraries has its own set of
  17. * getter functions, rules for handling missing values, and degree to which it
  18. * can engage in fuzziness of types.
  19. *
  20. * Adapter has two main groups of methods:
  21. * - as_*() and *_size() virtual functions
  22. * - maybe_*() concrete functions
  23. *
  24. * Most interaction with Adapter will be done via the maybe_*() functions,
  25. * with or without strictness enabled depending on what constraint is being
  26. * checked.
  27. */
  28. class Adapter {
  29. public:
  30. virtual ~Adapter() = default;
  31. /**
  32. * @brief Get the jvalidate::adapter::Type that this adapter represents.
  33. * This represents the types recognized by json-schema:
  34. * null, bool, integer, number, string, array, object
  35. * This function is meant to be used internally - and not by any of the
  36. * Constraint objects.
  37. */
  38. virtual Type type() const = 0;
  39. /**
  40. * @brief Obtain an immutable copy of the current node.
  41. * Because an Adapter stores a reference to the underlying JSON, it cannot
  42. * be stored by e.g. a Const/Enum Constraint without risking a Segfault.
  43. */
  44. virtual std::unique_ptr<Const const> freeze() const = 0;
  45. /**
  46. * @brief Extract a boolean value from this JSON node.
  47. * @pre type() == Type::Boolean
  48. *
  49. * @throws If the pre-condition is not valid, then this function may throw
  50. * or produce other undefined behavior, depending on the implementation
  51. * details of the underlying type.
  52. */
  53. virtual bool as_boolean() const = 0;
  54. /**
  55. * @brief Extract an integer value from this JSON node.
  56. * @pre type() == Type::Integer
  57. *
  58. * @throws If the pre-condition is not valid, then this function may throw
  59. * or produce other undefined behavior, depending on the implementation
  60. * details of the underlying type.
  61. */
  62. virtual int64_t as_integer() const = 0;
  63. /**
  64. * @brief Extract a decimal value from this JSON node.
  65. * @pre type() == Type::Number
  66. *
  67. * @throws If the pre-condition is not valid, then this function may throw
  68. * or produce other undefined behavior, depending on the implementation
  69. * details of the underlying type.
  70. */
  71. virtual double as_number() const = 0;
  72. /**
  73. * @brief Extract a string value from this JSON node.
  74. * @pre type() == Type::String
  75. *
  76. * @throws If the pre-condition is not valid, then this function may throw
  77. * or produce other undefined behavior, depending on the implementation
  78. * details of the underlying type.
  79. */
  80. virtual std::string as_string() const = 0;
  81. /**
  82. * @brief Get the size of the JSON array in this node.
  83. * @pre type() == Type::Array
  84. *
  85. * @throws If the pre-condition is not valid, then this function may throw
  86. * or produce other undefined behavior, depending on the implementation
  87. * details of the underlying type.
  88. */
  89. virtual size_t array_size() const = 0;
  90. /**
  91. * @brief Get the size of the JSON object in this node.
  92. * @pre type() == Type::Object
  93. *
  94. * @throws If the pre-condition is not valid, then this function may throw
  95. * or produce other undefined behavior, depending on the implementation
  96. * details of the underlying type.
  97. */
  98. virtual size_t object_size() const = 0;
  99. /**
  100. * @brief Loop through every element of the JSON array in this node, applying
  101. * the given callback function to them.
  102. *
  103. * @param cb A callback of the form Adapter => Status
  104. *
  105. * @return Status::Accept iff there are no errors
  106. */
  107. virtual Status apply_array(AdapterCallback const & cb) const = 0;
  108. /**
  109. * @brief Loop through every element of the JSON object in this node, applying
  110. * the given callback function to them.
  111. *
  112. * @param cb A callback of the form (string, Adapter) => Status
  113. *
  114. * @return Status::Accept iff there are no errors
  115. */
  116. virtual Status apply_object(ObjectAdapterCallback const & cb) const = 0;
  117. virtual bool equals(Adapter const & lhs, bool strict) const = 0;
  118. /**
  119. * @brief Test if this object is null-like
  120. *
  121. * @param strict Does this function allow for fuzzy comparisons with strings?
  122. */
  123. bool maybe_null(bool strict) const {
  124. switch (type()) {
  125. case Type::Null:
  126. return true;
  127. case Type::String:
  128. return not strict and as_string().empty();
  129. default:
  130. return false;
  131. }
  132. }
  133. /**
  134. * @brief Attempts to extract a boolean value from this JSON node
  135. *
  136. * @param strict Does this function allow for fuzzy comparisons with strings?
  137. *
  138. * @return The boolean value contained if it is possible to deduce
  139. * (or type() == Type::Boolean), else nullopt.
  140. */
  141. std::optional<bool> maybe_boolean(bool strict) const {
  142. switch (type()) {
  143. case Type::Boolean:
  144. return as_boolean();
  145. case Type::String:
  146. if (not strict) {
  147. auto str = as_string();
  148. if (str == "true") {
  149. return true;
  150. }
  151. if (str == "false") {
  152. return false;
  153. }
  154. }
  155. return std::nullopt;
  156. default:
  157. return std::nullopt;
  158. }
  159. }
  160. /**
  161. * @brief Attempts to extract a integer value from this JSON node
  162. *
  163. * @param strict Does this function allow for fuzzy comparisons with strings
  164. * and/or booleans?
  165. *
  166. * @return The integer value contained if it is possible to deduce from an
  167. * integer, number, boolean, or string. Else nullopt
  168. */
  169. std::optional<int64_t> maybe_integer(bool strict) const {
  170. switch (type()) {
  171. case Type::Number:
  172. if (double value = as_number(); jvalidate::detail::fits_in_integer(value)) {
  173. return static_cast<int64_t>(value);
  174. }
  175. return std::nullopt;
  176. case Type::Integer:
  177. return as_integer();
  178. case Type::Boolean:
  179. if (not strict) {
  180. return as_boolean() ? 1 : 0;
  181. }
  182. return std::nullopt;
  183. case Type::String:
  184. if (not strict) {
  185. auto str = as_string();
  186. size_t end = 0;
  187. int64_t rval = std::stoll(str, &end);
  188. if (end == str.size()) {
  189. return rval;
  190. }
  191. }
  192. return std::nullopt;
  193. default:
  194. return std::nullopt;
  195. }
  196. }
  197. /**
  198. * @brief Attempts to extract a number value from this JSON node
  199. *
  200. * @param strict Does this function allow for fuzzy comparisons with strings?
  201. *
  202. * @return The number value contained if it is possible to deduce
  203. * (or type() == Type::Integer || type() == Type::Number), else nullopt.
  204. */
  205. std::optional<double> maybe_number(bool strict) const {
  206. switch (type()) {
  207. case Type::Number:
  208. return as_number();
  209. case Type::Integer:
  210. return as_integer();
  211. case Type::String:
  212. if (not strict) {
  213. auto str = as_string();
  214. size_t end = 0;
  215. double rval = std::stod(str, &end);
  216. if (end == str.size()) {
  217. return rval;
  218. }
  219. }
  220. return std::nullopt;
  221. default:
  222. return std::nullopt;
  223. }
  224. }
  225. /**
  226. * @brief Attempts to extract a string value from this JSON node
  227. *
  228. * @param strict Does this function allow for fuzzy comparisons with other
  229. * types?
  230. *
  231. * @return The string value contained if it is possible to deduce from a
  232. * scalar type, else nullopt.
  233. */
  234. std::optional<std::string> maybe_string(bool strict) const {
  235. switch (type()) {
  236. case Type::Null:
  237. return strict ? std::nullopt : std::make_optional("");
  238. case Type::String:
  239. return as_string();
  240. case Type::Number:
  241. if (not strict) {
  242. return std::to_string(as_number());
  243. }
  244. return std::nullopt;
  245. case Type::Integer:
  246. if (not strict) {
  247. return std::to_string(as_integer());
  248. }
  249. return std::nullopt;
  250. case Type::Boolean:
  251. if (not strict) {
  252. return as_boolean() ? "true" : "false";
  253. }
  254. return std::nullopt;
  255. default:
  256. return std::nullopt;
  257. }
  258. }
  259. /**
  260. * @brief Attempts to extract the array length from this JSON node
  261. *
  262. * @param strict Does this function allow for fuzzy comparisons with other
  263. * types?
  264. *
  265. * @return array_size() if this is an array, else 0 or nullopt, depending
  266. * on some factors.
  267. */
  268. std::optional<size_t> maybe_array_size(bool strict) const {
  269. switch (type()) {
  270. case Type::Array:
  271. return array_size();
  272. case Type::Null:
  273. return strict ? std::nullopt : std::make_optional(0UL);
  274. case Type::Object:
  275. return (strict || object_size() != 0) ? std::nullopt : std::make_optional(0UL);
  276. default:
  277. return std::nullopt;
  278. }
  279. }
  280. /**
  281. * @brief Attempts to extract the object length from this JSON node
  282. *
  283. * @param strict Does this function allow for fuzzy comparisons with other
  284. * types?
  285. *
  286. * @return object_size() if this is an object, else 0 or nullopt, depending
  287. * on some factors.
  288. */
  289. std::optional<size_t> maybe_object_size(bool strict) const {
  290. switch (type()) {
  291. case Type::Object:
  292. return object_size();
  293. case Type::Null:
  294. return strict ? std::nullopt : std::make_optional(0UL);
  295. case Type::Array:
  296. return (strict || array_size() != 0) ? std::nullopt : std::make_optional(0UL);
  297. default:
  298. return std::nullopt;
  299. }
  300. }
  301. virtual void write(std::ostream & os) const {
  302. std::string_view div;
  303. switch (type()) {
  304. case Type::Null:
  305. os << "null";
  306. break;
  307. case Type::Boolean:
  308. os << (as_boolean() ? "true" : "false");
  309. break;
  310. case Type::Integer:
  311. os << as_integer();
  312. break;
  313. case Type::Number:
  314. os << as_number();
  315. break;
  316. case Type::String:
  317. os << '"' << as_string() << '"';
  318. break;
  319. case Type::Array:
  320. os << '[';
  321. apply_array([&os, &div](Adapter const & elem) {
  322. os << std::exchange(div, ", ") << elem;
  323. return Status::Accept;
  324. });
  325. os << ']';
  326. break;
  327. case Type::Object:
  328. os << '{';
  329. apply_object([&os, &div](std::string const & key, Adapter const & elem) {
  330. os << std::exchange(div, ", ") << '"' << key << '"' << ':' << elem;
  331. return Status::Accept;
  332. });
  333. os << '}';
  334. break;
  335. }
  336. }
  337. friend std::ostream & operator<<(std::ostream & os, Adapter const & self) {
  338. self.write(os);
  339. return os;
  340. }
  341. };
  342. /**
  343. * @brief An interface for an immutable, owning handle to a type-erased JSON
  344. * node. {@see Adapter::freeze} for more explaination why this is necessary.
  345. */
  346. class Const {
  347. public:
  348. virtual ~Const() = default;
  349. /**
  350. * @brief Perform an action on this object, such as copying or testing
  351. * equality.
  352. *
  353. * @param cb A callback function of the form Adapter => Status
  354. *
  355. * @return the result of cb on the contained JSON
  356. */
  357. virtual Status apply(AdapterCallback const & cb) const = 0;
  358. friend std::ostream & operator<<(std::ostream & os, Const const & self) {
  359. self.apply([&os](Adapter const & adapter) {
  360. adapter.write(os);
  361. return Status::Accept;
  362. });
  363. return os;
  364. }
  365. };
  366. }
  367. namespace jvalidate::adapter::detail {
  368. /**
  369. * @brief The simplest implementation of Const.
  370. * Depends on the AdapterTraits struct.
  371. *
  372. * @tparam JSON The type being adapted
  373. */
  374. template <typename JSON> class GenericConst final : public Const {
  375. public:
  376. explicit GenericConst(JSON const & value) : value_(value) {}
  377. Status apply(AdapterCallback const & cb) const {
  378. return cb(typename AdapterTraits<JSON>::ConstAdapter(value_));
  379. }
  380. JSON const & value() const { return value_; }
  381. private:
  382. JSON value_;
  383. };
  384. }
  385. namespace std {
  386. inline ostream & operator<<(ostream & os,
  387. vector<unique_ptr<jvalidate::adapter::Const const>> const & items) {
  388. std::string_view div;
  389. os << '[';
  390. for (auto const & ptr : items) {
  391. os << std::exchange(div, ", ") << *ptr;
  392. }
  393. return os << ']';
  394. }
  395. }