adapter.h 12 KB

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