value_stack.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. //
  2. // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/json
  8. //
  9. #ifndef BOOST_JSON_VALUE_STACK_HPP
  10. #define BOOST_JSON_VALUE_STACK_HPP
  11. #include <boost/json/detail/config.hpp>
  12. #include <boost/json/error.hpp>
  13. #include <boost/json/storage_ptr.hpp>
  14. #include <boost/json/value.hpp>
  15. #include <stddef.h>
  16. BOOST_JSON_NS_BEGIN
  17. //----------------------------------------------------------
  18. /** A stack of @ref value elements, for building a document.
  19. This stack of @ref value allows iterative
  20. construction of a JSON document in memory.
  21. The implementation uses temporary internal
  22. storage to buffer elements so that arrays, objects,
  23. and strings in the document are constructed using a
  24. single memory allocation. This improves performance
  25. and makes efficient use of the @ref memory_resource
  26. used to create the resulting @ref value.
  27. Temporary storage used by the implementation
  28. initially comes from an optional memory buffer
  29. owned by the caller. If that storage is exhausted,
  30. then memory is obtained dynamically from the
  31. @ref memory_resource provided on construction.
  32. @par Usage
  33. Construct the stack with an optional initial
  34. temporary buffer, and a @ref storage_ptr to use for
  35. more storage when the initial buffer is exhausted.
  36. Then to build a @ref value, first call @ref reset
  37. and optionally specify the @ref memory_resource
  38. which will be used for the value. Then push elements
  39. onto the stack by calling the corresponding functions.
  40. After the document has been fully created, call
  41. @ref release to acquire ownership of the top-level
  42. @ref value.
  43. @par Performance
  44. The initial buffer and any dynamically allocated
  45. temporary buffers are retained until the stack
  46. is destroyed. This improves performance when using
  47. a single stack instance to produce multiple
  48. values.
  49. @par Example
  50. The following code constructs a @ref value which
  51. when serialized produces a JSON object with three
  52. elements. It uses a local buffer for the temporary
  53. storage, and a separate local buffer for the storage
  54. of the resulting value. No memory is dynamically
  55. allocated; this shows how to construct a value
  56. without using the heap.
  57. @code
  58. // This example builds a json::value without any dynamic memory allocations:
  59. // Construct the value stack using a local buffer
  60. unsigned char temp[4096];
  61. value_stack st( storage_ptr(), temp, sizeof(temp) );
  62. // Create a static resource with a local initial buffer
  63. unsigned char buf[4096];
  64. static_resource mr( buf, sizeof(buf) );
  65. // All values on the stack will use `mr`
  66. st.reset(&mr);
  67. // Push the key/value pair "a":1.
  68. st.push_key("a");
  69. st.push_int64(1);
  70. // Push "b":null
  71. st.push_key("b");
  72. st.push_null();
  73. // Push "c":"hello"
  74. st.push_key("c");
  75. st.push_string("hello");
  76. // Pop the three key/value pairs and push an object with those three values.
  77. st.push_object(3);
  78. // Pop the object from the stack and take ownership.
  79. value jv = st.release();
  80. assert( serialize(jv) == "{\"a\":1,\"b\":null,\"c\":\"hello\"}" );
  81. // At this point we could re-use the stack by calling reset
  82. @endcode
  83. @par Thread Safety
  84. Distinct instances may be accessed concurrently.
  85. Non-const member functions of a shared instance
  86. may not be called concurrently with any other
  87. member functions of that instance.
  88. */
  89. class value_stack
  90. {
  91. class stack
  92. {
  93. enum
  94. {
  95. min_size_ = 16
  96. };
  97. storage_ptr sp_;
  98. void* temp_;
  99. value* begin_;
  100. value* top_;
  101. value* end_;
  102. // string starts at top_+1
  103. std::size_t chars_ = 0;
  104. bool run_dtors_ = true;
  105. public:
  106. inline ~stack();
  107. inline stack(
  108. storage_ptr sp,
  109. void* temp, std::size_t size) noexcept;
  110. inline void run_dtors(bool b) noexcept;
  111. inline std::size_t size() const noexcept;
  112. inline bool has_chars();
  113. inline void clear() noexcept;
  114. inline void maybe_grow();
  115. inline void grow_one();
  116. inline void grow(std::size_t nchars);
  117. inline void append(string_view s);
  118. inline string_view release_string() noexcept;
  119. inline value* release(std::size_t n) noexcept;
  120. template<class... Args> value& push(Args&&... args);
  121. template<class Unchecked> void exchange(Unchecked&& u);
  122. };
  123. stack st_;
  124. storage_ptr sp_;
  125. public:
  126. /// Copy constructor (deleted)
  127. value_stack(
  128. value_stack const&) = delete;
  129. /// Copy assignment (deleted)
  130. value_stack& operator=(
  131. value_stack const&) = delete;
  132. /** Destructor.
  133. All dynamically allocated memory and
  134. partial or complete elements is freed.
  135. @par Complexity
  136. Linear in the size of partial results.
  137. @par Exception Safety
  138. No-throw guarantee.
  139. */
  140. BOOST_JSON_DECL
  141. ~value_stack();
  142. /** Constructor.
  143. Constructs an empty stack. Before any
  144. @ref value can be built, the function
  145. @ref reset must be called.
  146. The `sp` parameter is only used to allocate
  147. intermediate storage; it will not be used
  148. for the @ref value returned by @ref release.
  149. @param sp A pointer to the @ref memory_resource
  150. to use for intermediate storage allocations. If
  151. this argument is omitted, the default memory
  152. resource is used.
  153. @param temp_buffer A pointer to a caller-owned
  154. buffer which will be used to store temporary
  155. data used while building the value. If this
  156. pointer is null, the builder will use the
  157. storage pointer to allocate temporary data.
  158. @param temp_size The number of valid bytes of
  159. storage pointed to by `temp_buffer`.
  160. */
  161. BOOST_JSON_DECL
  162. value_stack(
  163. storage_ptr sp = {},
  164. unsigned char* temp_buffer = nullptr,
  165. std::size_t temp_size = 0) noexcept;
  166. /** Prepare to build a new document.
  167. This function must be called before constructing
  168. a new top-level @ref value. Any previously existing
  169. partial or complete elements are destroyed, but
  170. internal dynamically allocated memory is preserved
  171. which may be reused to build new values.
  172. @par Exception Safety
  173. No-throw guarantee.
  174. @param sp A pointer to the @ref memory_resource
  175. to use for top-level @ref value and all child
  176. values. The stack will acquire shared ownership
  177. of the memory resource until @ref release or
  178. @ref reset is called, or when the stack is
  179. destroyed.
  180. */
  181. BOOST_JSON_DECL
  182. void
  183. reset(storage_ptr sp = {}) noexcept;
  184. /** Return the top-level @ref value.
  185. This function transfers ownership of the
  186. constructed top-level value to the caller.
  187. The behavior is undefined if there is not
  188. a single, top-level element.
  189. @par Exception Safety
  190. No-throw guarantee.
  191. @return A __value__ holding the result.
  192. Ownership of this value is transferred
  193. to the caller. Ownership of the memory
  194. resource used in the last call to @ref reset
  195. is released.
  196. */
  197. BOOST_JSON_DECL
  198. value
  199. release() noexcept;
  200. //--------------------------------------------
  201. /** Push an array formed by popping `n` values from the stack.
  202. This function pushes an @ref array value
  203. onto the stack. The array is formed by first
  204. popping the top `n` values from the stack.
  205. If the stack contains fewer than `n` values,
  206. or if any of the top `n` values on the stack
  207. is a key, the behavior is undefined.
  208. @par Example
  209. The following statements produce an array
  210. with the contents 1, 2, 3:
  211. @code
  212. value_stack st;
  213. // reset must be called first or else the behavior is undefined
  214. st.reset();
  215. // Place three values on the stack
  216. st.push_int64( 1 );
  217. st.push_int64( 2 );
  218. st.push_int64( 3 );
  219. // Remove the 3 values, and push an array with those 3 elements on the stack
  220. st.push_array( 3 );
  221. // Pop the object from the stack and take ownership.
  222. value jv = st.release();
  223. assert( serialize(jv) == "[1,2,3]" );
  224. // At this point, reset must be called again to use the stack
  225. @endcode
  226. @param n The number of values to pop from the
  227. top of the stack to form the array.
  228. */
  229. BOOST_JSON_DECL
  230. void
  231. push_array(std::size_t n);
  232. /** Push an object formed by popping `n` key/value pairs from the stack.
  233. This function pushes an @ref object value
  234. onto the stack. The object is formed by first
  235. popping the top `n` key/value pairs from the
  236. stack. If the stack contains fewer than `n`
  237. key/value pairs, or if any of the top `n` key/value
  238. pairs on the stack does not consist of exactly one
  239. key followed by one value, the behavior is undefined.
  240. @note
  241. A key/value pair is formed by pushing a key, and then
  242. pushing a value.
  243. @par Example
  244. The following code creates an object on the stack
  245. with a single element, where key is "x" and value
  246. is true:
  247. @code
  248. value_stack st;
  249. // reset must be called first or else the behavior is undefined
  250. st.reset();
  251. // Place a key/value pair onto the stack
  252. st.push_key( "x" );
  253. st.push_bool( true );
  254. // Replace the key/value pair with an object containing a single element
  255. st.push_object( 1 );
  256. // Pop the object from the stack and take ownership.
  257. value jv = st.release();
  258. assert( serialize(jv) == "{\"x\",true}" );
  259. // At this point, reset must be called again to use the stack
  260. @endcode
  261. @par Duplicate Keys
  262. If there are object elements with duplicate keys;
  263. that is, if multiple elements in an object have
  264. keys that compare equal, only the last equivalent
  265. element will be inserted.
  266. @param n The number of key/value pairs to pop from the
  267. top of the stack to form the array.
  268. */
  269. BOOST_JSON_DECL
  270. void
  271. push_object(std::size_t n);
  272. /** Push part of a key or string onto the stack.
  273. This function pushes the characters in `s` onto
  274. the stack, appending to any existing characters
  275. or creating new characters as needed. Once a
  276. string part is placed onto the stack, the only
  277. valid stack operations are:
  278. @li @ref push_chars to append additional
  279. characters to the key or string being built,
  280. @li @ref push_key or @ref push_string to
  281. finish building the key or string and place
  282. the value onto the stack.
  283. @par Exception Safety
  284. Basic guarantee.
  285. Calls to `memory_resource::allocate` may throw.
  286. @param s The characters to append. This may be empty.
  287. */
  288. BOOST_JSON_DECL
  289. void
  290. push_chars(
  291. string_view s);
  292. /** Push a key onto the stack.
  293. This function notionally removes all the
  294. characters currently on the stack, then
  295. pushes a @ref value containing a key onto
  296. the stack formed by appending `s` to the
  297. removed characters.
  298. @par Exception Safety
  299. Basic guarantee.
  300. Calls to `memory_resource::allocate` may throw.
  301. @param s The characters to append. This may be empty.
  302. */
  303. BOOST_JSON_DECL
  304. void
  305. push_key(
  306. string_view s);
  307. /** Place a string value onto the stack.
  308. This function notionally removes all the
  309. characters currently on the stack, then
  310. pushes a @ref value containing a @ref string
  311. onto the stack formed by appending `s` to the
  312. removed characters.
  313. @par Exception Safety
  314. Basic guarantee.
  315. Calls to `memory_resource::allocate` may throw.
  316. @param s The characters to append. This may be empty.
  317. */
  318. BOOST_JSON_DECL
  319. void
  320. push_string(
  321. string_view s);
  322. /** Push a number onto the stack
  323. This function pushes a number value onto the stack.
  324. @par Exception Safety
  325. Basic guarantee.
  326. Calls to `memory_resource::allocate` may throw.
  327. @param i The number to insert.
  328. */
  329. BOOST_JSON_DECL
  330. void
  331. push_int64(
  332. int64_t i);
  333. /** Push a number onto the stack
  334. This function pushes a number value onto the stack.
  335. @par Exception Safety
  336. Basic guarantee.
  337. Calls to `memory_resource::allocate` may throw.
  338. @param u The number to insert.
  339. */
  340. BOOST_JSON_DECL
  341. void
  342. push_uint64(
  343. uint64_t u);
  344. /** Push a number onto the stack
  345. This function pushes a number value onto the stack.
  346. @par Exception Safety
  347. Basic guarantee.
  348. Calls to `memory_resource::allocate` may throw.
  349. @param d The number to insert.
  350. */
  351. BOOST_JSON_DECL
  352. void
  353. push_double(
  354. double d);
  355. /** Push a `bool` onto the stack
  356. This function pushes a boolean value onto the stack.
  357. @par Exception Safety
  358. Basic guarantee.
  359. Calls to `memory_resource::allocate` may throw.
  360. @param b The boolean to insert.
  361. */
  362. BOOST_JSON_DECL
  363. void
  364. push_bool(
  365. bool b);
  366. /** Push a null onto the stack
  367. This function pushes a boolean value onto the stack.
  368. @par Exception Safety
  369. Basic guarantee.
  370. Calls to `memory_resource::allocate` may throw.
  371. */
  372. BOOST_JSON_DECL
  373. void
  374. push_null();
  375. };
  376. BOOST_JSON_NS_END
  377. #endif