adapter.h 12 KB

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