document.h 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef CEREAL_RAPIDJSON_DOCUMENT_H_
  15. #define CEREAL_RAPIDJSON_DOCUMENT_H_
  16. /*! \file document.h */
  17. #include "reader.h"
  18. #include "internal/meta.h"
  19. #include "internal/strfunc.h"
  20. #include "memorystream.h"
  21. #include "encodedstream.h"
  22. #include <new> // placement new
  23. #include <limits>
  24. #ifdef __cpp_lib_three_way_comparison
  25. #include <compare>
  26. #endif
  27. CEREAL_RAPIDJSON_DIAG_PUSH
  28. #ifdef __clang__
  29. CEREAL_RAPIDJSON_DIAG_OFF(padded)
  30. CEREAL_RAPIDJSON_DIAG_OFF(switch-enum)
  31. CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat)
  32. #elif defined(_MSC_VER)
  33. CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  34. CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data
  35. #endif
  36. #ifdef __GNUC__
  37. CEREAL_RAPIDJSON_DIAG_OFF(effc++)
  38. #endif // __GNUC__
  39. #ifndef CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS
  40. #include <iterator> // std::random_access_iterator_tag
  41. #endif
  42. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  43. #include <utility> // std::move
  44. #endif
  45. CEREAL_RAPIDJSON_NAMESPACE_BEGIN
  46. // Forward declaration.
  47. template <typename Encoding, typename Allocator>
  48. class GenericValue;
  49. template <typename Encoding, typename Allocator, typename StackAllocator>
  50. class GenericDocument;
  51. //! Name-value pair in a JSON object value.
  52. /*!
  53. This class was internal to GenericValue. It used to be a inner struct.
  54. But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct.
  55. https://code.google.com/p/rapidjson/issues/detail?id=64
  56. */
  57. template <typename Encoding, typename Allocator>
  58. struct GenericMember {
  59. GenericValue<Encoding, Allocator> name; //!< name of member (must be a string)
  60. GenericValue<Encoding, Allocator> value; //!< value of member.
  61. // swap() for std::sort() and other potential use in STL.
  62. friend inline void swap(GenericMember& a, GenericMember& b) CEREAL_RAPIDJSON_NOEXCEPT {
  63. a.name.Swap(b.name);
  64. a.value.Swap(b.value);
  65. }
  66. };
  67. ///////////////////////////////////////////////////////////////////////////////
  68. // GenericMemberIterator
  69. #ifndef CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS
  70. //! (Constant) member iterator for a JSON object value
  71. /*!
  72. \tparam Const Is this a constant iterator?
  73. \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
  74. \tparam Allocator Allocator type for allocating memory of object, array and string.
  75. This class implements a Random Access Iterator for GenericMember elements
  76. of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements].
  77. \note This iterator implementation is mainly intended to avoid implicit
  78. conversions from iterator values to \c NULL,
  79. e.g. from GenericValue::FindMember.
  80. \note Define \c CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a
  81. pointer-based implementation, if your platform doesn't provide
  82. the C++ <iterator> header.
  83. \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
  84. */
  85. template <bool Const, typename Encoding, typename Allocator>
  86. class GenericMemberIterator {
  87. friend class GenericValue<Encoding,Allocator>;
  88. template <bool, typename, typename> friend class GenericMemberIterator;
  89. typedef GenericMember<Encoding,Allocator> PlainType;
  90. typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
  91. public:
  92. //! Iterator type itself
  93. typedef GenericMemberIterator Iterator;
  94. //! Constant iterator type
  95. typedef GenericMemberIterator<true,Encoding,Allocator> ConstIterator;
  96. //! Non-constant iterator type
  97. typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator;
  98. /** \name std::iterator_traits support */
  99. //@{
  100. typedef ValueType value_type;
  101. typedef ValueType * pointer;
  102. typedef ValueType & reference;
  103. typedef std::ptrdiff_t difference_type;
  104. typedef std::random_access_iterator_tag iterator_category;
  105. //@}
  106. //! Pointer to (const) GenericMember
  107. typedef pointer Pointer;
  108. //! Reference to (const) GenericMember
  109. typedef reference Reference;
  110. //! Signed integer type (e.g. \c ptrdiff_t)
  111. typedef difference_type DifferenceType;
  112. //! Default constructor (singular value)
  113. /*! Creates an iterator pointing to no element.
  114. \note All operations, except for comparisons, are undefined on such values.
  115. */
  116. GenericMemberIterator() : ptr_() {}
  117. //! Iterator conversions to more const
  118. /*!
  119. \param it (Non-const) iterator to copy from
  120. Allows the creation of an iterator from another GenericMemberIterator
  121. that is "less const". Especially, creating a non-constant iterator
  122. from a constant iterator are disabled:
  123. \li const -> non-const (not ok)
  124. \li const -> const (ok)
  125. \li non-const -> const (ok)
  126. \li non-const -> non-const (ok)
  127. \note If the \c Const template parameter is already \c false, this
  128. constructor effectively defines a regular copy-constructor.
  129. Otherwise, the copy constructor is implicitly defined.
  130. */
  131. GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {}
  132. Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; }
  133. //! @name stepping
  134. //@{
  135. Iterator& operator++(){ ++ptr_; return *this; }
  136. Iterator& operator--(){ --ptr_; return *this; }
  137. Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; }
  138. Iterator operator--(int){ Iterator old(*this); --ptr_; return old; }
  139. //@}
  140. //! @name increment/decrement
  141. //@{
  142. Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); }
  143. Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); }
  144. Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; }
  145. Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; }
  146. //@}
  147. //! @name relations
  148. //@{
  149. template <bool Const_> bool operator==(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ == that.ptr_; }
  150. template <bool Const_> bool operator!=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ != that.ptr_; }
  151. template <bool Const_> bool operator<=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ <= that.ptr_; }
  152. template <bool Const_> bool operator>=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ >= that.ptr_; }
  153. template <bool Const_> bool operator< (const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ < that.ptr_; }
  154. template <bool Const_> bool operator> (const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ > that.ptr_; }
  155. #ifdef __cpp_lib_three_way_comparison
  156. template <bool Const_> std::strong_ordering operator<=>(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ <=> that.ptr_; }
  157. #endif
  158. //@}
  159. //! @name dereference
  160. //@{
  161. Reference operator*() const { return *ptr_; }
  162. Pointer operator->() const { return ptr_; }
  163. Reference operator[](DifferenceType n) const { return ptr_[n]; }
  164. //@}
  165. //! Distance
  166. DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; }
  167. private:
  168. //! Internal constructor from plain pointer
  169. explicit GenericMemberIterator(Pointer p) : ptr_(p) {}
  170. Pointer ptr_; //!< raw pointer
  171. };
  172. #else // CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS
  173. // class-based member iterator implementation disabled, use plain pointers
  174. template <bool Const, typename Encoding, typename Allocator>
  175. class GenericMemberIterator;
  176. //! non-const GenericMemberIterator
  177. template <typename Encoding, typename Allocator>
  178. class GenericMemberIterator<false,Encoding,Allocator> {
  179. //! use plain pointer as iterator type
  180. typedef GenericMember<Encoding,Allocator>* Iterator;
  181. };
  182. //! const GenericMemberIterator
  183. template <typename Encoding, typename Allocator>
  184. class GenericMemberIterator<true,Encoding,Allocator> {
  185. //! use plain const pointer as iterator type
  186. typedef const GenericMember<Encoding,Allocator>* Iterator;
  187. };
  188. #endif // CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS
  189. ///////////////////////////////////////////////////////////////////////////////
  190. // GenericStringRef
  191. //! Reference to a constant string (not taking a copy)
  192. /*!
  193. \tparam CharType character type of the string
  194. This helper class is used to automatically infer constant string
  195. references for string literals, especially from \c const \b (!)
  196. character arrays.
  197. The main use is for creating JSON string values without copying the
  198. source string via an \ref Allocator. This requires that the referenced
  199. string pointers have a sufficient lifetime, which exceeds the lifetime
  200. of the associated GenericValue.
  201. \b Example
  202. \code
  203. Value v("foo"); // ok, no need to copy & calculate length
  204. const char foo[] = "foo";
  205. v.SetString(foo); // ok
  206. const char* bar = foo;
  207. // Value x(bar); // not ok, can't rely on bar's lifetime
  208. Value x(StringRef(bar)); // lifetime explicitly guaranteed by user
  209. Value y(StringRef(bar, 3)); // ok, explicitly pass length
  210. \endcode
  211. \see StringRef, GenericValue::SetString
  212. */
  213. template<typename CharType>
  214. struct GenericStringRef {
  215. typedef CharType Ch; //!< character type of the string
  216. //! Create string reference from \c const character array
  217. #ifndef __clang__ // -Wdocumentation
  218. /*!
  219. This constructor implicitly creates a constant string reference from
  220. a \c const character array. It has better performance than
  221. \ref StringRef(const CharType*) by inferring the string \ref length
  222. from the array length, and also supports strings containing null
  223. characters.
  224. \tparam N length of the string, automatically inferred
  225. \param str Constant character array, lifetime assumed to be longer
  226. than the use of the string in e.g. a GenericValue
  227. \post \ref s == str
  228. \note Constant complexity.
  229. \note There is a hidden, private overload to disallow references to
  230. non-const character arrays to be created via this constructor.
  231. By this, e.g. function-scope arrays used to be filled via
  232. \c snprintf are excluded from consideration.
  233. In such cases, the referenced string should be \b copied to the
  234. GenericValue instead.
  235. */
  236. #endif
  237. template<SizeType N>
  238. GenericStringRef(const CharType (&str)[N]) CEREAL_RAPIDJSON_NOEXCEPT
  239. : s(str), length(N-1) {}
  240. //! Explicitly create string reference from \c const character pointer
  241. #ifndef __clang__ // -Wdocumentation
  242. /*!
  243. This constructor can be used to \b explicitly create a reference to
  244. a constant string pointer.
  245. \see StringRef(const CharType*)
  246. \param str Constant character pointer, lifetime assumed to be longer
  247. than the use of the string in e.g. a GenericValue
  248. \post \ref s == str
  249. \note There is a hidden, private overload to disallow references to
  250. non-const character arrays to be created via this constructor.
  251. By this, e.g. function-scope arrays used to be filled via
  252. \c snprintf are excluded from consideration.
  253. In such cases, the referenced string should be \b copied to the
  254. GenericValue instead.
  255. */
  256. #endif
  257. explicit GenericStringRef(const CharType* str)
  258. : s(str), length(NotNullStrLen(str)) {}
  259. //! Create constant string reference from pointer and length
  260. #ifndef __clang__ // -Wdocumentation
  261. /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
  262. \param len length of the string, excluding the trailing NULL terminator
  263. \post \ref s == str && \ref length == len
  264. \note Constant complexity.
  265. */
  266. #endif
  267. GenericStringRef(const CharType* str, SizeType len)
  268. : s(CEREAL_RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { CEREAL_RAPIDJSON_ASSERT(str != 0 || len == 0u); }
  269. GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {}
  270. //! implicit conversion to plain CharType pointer
  271. operator const Ch *() const { return s; }
  272. const Ch* const s; //!< plain CharType pointer
  273. const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
  274. private:
  275. SizeType NotNullStrLen(const CharType* str) {
  276. CEREAL_RAPIDJSON_ASSERT(str != 0);
  277. return internal::StrLen(str);
  278. }
  279. /// Empty string - used when passing in a NULL pointer
  280. static const Ch emptyString[];
  281. //! Disallow construction from non-const array
  282. template<SizeType N>
  283. GenericStringRef(CharType (&str)[N]) /* = delete */;
  284. //! Copy assignment operator not permitted - immutable type
  285. GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */;
  286. };
  287. template<typename CharType>
  288. const CharType GenericStringRef<CharType>::emptyString[] = { CharType() };
  289. //! Mark a character pointer as constant string
  290. /*! Mark a plain character pointer as a "string literal". This function
  291. can be used to avoid copying a character string to be referenced as a
  292. value in a JSON GenericValue object, if the string's lifetime is known
  293. to be valid long enough.
  294. \tparam CharType Character type of the string
  295. \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
  296. \return GenericStringRef string reference object
  297. \relatesalso GenericStringRef
  298. \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember
  299. */
  300. template<typename CharType>
  301. inline GenericStringRef<CharType> StringRef(const CharType* str) {
  302. return GenericStringRef<CharType>(str);
  303. }
  304. //! Mark a character pointer as constant string
  305. /*! Mark a plain character pointer as a "string literal". This function
  306. can be used to avoid copying a character string to be referenced as a
  307. value in a JSON GenericValue object, if the string's lifetime is known
  308. to be valid long enough.
  309. This version has better performance with supplied length, and also
  310. supports string containing null characters.
  311. \tparam CharType character type of the string
  312. \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
  313. \param length The length of source string.
  314. \return GenericStringRef string reference object
  315. \relatesalso GenericStringRef
  316. */
  317. template<typename CharType>
  318. inline GenericStringRef<CharType> StringRef(const CharType* str, size_t length) {
  319. return GenericStringRef<CharType>(str, SizeType(length));
  320. }
  321. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  322. //! Mark a string object as constant string
  323. /*! Mark a string object (e.g. \c std::string) as a "string literal".
  324. This function can be used to avoid copying a string to be referenced as a
  325. value in a JSON GenericValue object, if the string's lifetime is known
  326. to be valid long enough.
  327. \tparam CharType character type of the string
  328. \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
  329. \return GenericStringRef string reference object
  330. \relatesalso GenericStringRef
  331. \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING.
  332. */
  333. template<typename CharType>
  334. inline GenericStringRef<CharType> StringRef(const std::basic_string<CharType>& str) {
  335. return GenericStringRef<CharType>(str.data(), SizeType(str.size()));
  336. }
  337. #endif
  338. ///////////////////////////////////////////////////////////////////////////////
  339. // GenericValue type traits
  340. namespace internal {
  341. template <typename T, typename Encoding = void, typename Allocator = void>
  342. struct IsGenericValueImpl : FalseType {};
  343. // select candidates according to nested encoding and allocator types
  344. template <typename T> struct IsGenericValueImpl<T, typename Void<typename T::EncodingType>::Type, typename Void<typename T::AllocatorType>::Type>
  345. : IsBaseOf<GenericValue<typename T::EncodingType, typename T::AllocatorType>, T>::Type {};
  346. // helper to match arbitrary GenericValue instantiations, including derived classes
  347. template <typename T> struct IsGenericValue : IsGenericValueImpl<T>::Type {};
  348. } // namespace internal
  349. ///////////////////////////////////////////////////////////////////////////////
  350. // TypeHelper
  351. namespace internal {
  352. template <typename ValueType, typename T>
  353. struct TypeHelper {};
  354. template<typename ValueType>
  355. struct TypeHelper<ValueType, bool> {
  356. static bool Is(const ValueType& v) { return v.IsBool(); }
  357. static bool Get(const ValueType& v) { return v.GetBool(); }
  358. static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); }
  359. static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); }
  360. };
  361. template<typename ValueType>
  362. struct TypeHelper<ValueType, int> {
  363. static bool Is(const ValueType& v) { return v.IsInt(); }
  364. static int Get(const ValueType& v) { return v.GetInt(); }
  365. static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); }
  366. static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); }
  367. };
  368. template<typename ValueType>
  369. struct TypeHelper<ValueType, unsigned> {
  370. static bool Is(const ValueType& v) { return v.IsUint(); }
  371. static unsigned Get(const ValueType& v) { return v.GetUint(); }
  372. static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); }
  373. static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); }
  374. };
  375. #ifdef _MSC_VER
  376. CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int));
  377. template<typename ValueType>
  378. struct TypeHelper<ValueType, long> {
  379. static bool Is(const ValueType& v) { return v.IsInt(); }
  380. static long Get(const ValueType& v) { return v.GetInt(); }
  381. static ValueType& Set(ValueType& v, long data) { return v.SetInt(data); }
  382. static ValueType& Set(ValueType& v, long data, typename ValueType::AllocatorType&) { return v.SetInt(data); }
  383. };
  384. CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned));
  385. template<typename ValueType>
  386. struct TypeHelper<ValueType, unsigned long> {
  387. static bool Is(const ValueType& v) { return v.IsUint(); }
  388. static unsigned long Get(const ValueType& v) { return v.GetUint(); }
  389. static ValueType& Set(ValueType& v, unsigned long data) { return v.SetUint(data); }
  390. static ValueType& Set(ValueType& v, unsigned long data, typename ValueType::AllocatorType&) { return v.SetUint(data); }
  391. };
  392. #endif
  393. template<typename ValueType>
  394. struct TypeHelper<ValueType, int64_t> {
  395. static bool Is(const ValueType& v) { return v.IsInt64(); }
  396. static int64_t Get(const ValueType& v) { return v.GetInt64(); }
  397. static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); }
  398. static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); }
  399. };
  400. template<typename ValueType>
  401. struct TypeHelper<ValueType, uint64_t> {
  402. static bool Is(const ValueType& v) { return v.IsUint64(); }
  403. static uint64_t Get(const ValueType& v) { return v.GetUint64(); }
  404. static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); }
  405. static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); }
  406. };
  407. template<typename ValueType>
  408. struct TypeHelper<ValueType, double> {
  409. static bool Is(const ValueType& v) { return v.IsDouble(); }
  410. static double Get(const ValueType& v) { return v.GetDouble(); }
  411. static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); }
  412. static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); }
  413. };
  414. template<typename ValueType>
  415. struct TypeHelper<ValueType, float> {
  416. static bool Is(const ValueType& v) { return v.IsFloat(); }
  417. static float Get(const ValueType& v) { return v.GetFloat(); }
  418. static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); }
  419. static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); }
  420. };
  421. template<typename ValueType>
  422. struct TypeHelper<ValueType, const typename ValueType::Ch*> {
  423. typedef const typename ValueType::Ch* StringType;
  424. static bool Is(const ValueType& v) { return v.IsString(); }
  425. static StringType Get(const ValueType& v) { return v.GetString(); }
  426. static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); }
  427. static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
  428. };
  429. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  430. template<typename ValueType>
  431. struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > {
  432. typedef std::basic_string<typename ValueType::Ch> StringType;
  433. static bool Is(const ValueType& v) { return v.IsString(); }
  434. static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); }
  435. static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
  436. };
  437. #endif
  438. template<typename ValueType>
  439. struct TypeHelper<ValueType, typename ValueType::Array> {
  440. typedef typename ValueType::Array ArrayType;
  441. static bool Is(const ValueType& v) { return v.IsArray(); }
  442. static ArrayType Get(ValueType& v) { return v.GetArray(); }
  443. static ValueType& Set(ValueType& v, ArrayType data) { return v = data; }
  444. static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; }
  445. };
  446. template<typename ValueType>
  447. struct TypeHelper<ValueType, typename ValueType::ConstArray> {
  448. typedef typename ValueType::ConstArray ArrayType;
  449. static bool Is(const ValueType& v) { return v.IsArray(); }
  450. static ArrayType Get(const ValueType& v) { return v.GetArray(); }
  451. };
  452. template<typename ValueType>
  453. struct TypeHelper<ValueType, typename ValueType::Object> {
  454. typedef typename ValueType::Object ObjectType;
  455. static bool Is(const ValueType& v) { return v.IsObject(); }
  456. static ObjectType Get(ValueType& v) { return v.GetObject(); }
  457. static ValueType& Set(ValueType& v, ObjectType data) { return v = data; }
  458. static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; }
  459. };
  460. template<typename ValueType>
  461. struct TypeHelper<ValueType, typename ValueType::ConstObject> {
  462. typedef typename ValueType::ConstObject ObjectType;
  463. static bool Is(const ValueType& v) { return v.IsObject(); }
  464. static ObjectType Get(const ValueType& v) { return v.GetObject(); }
  465. };
  466. } // namespace internal
  467. // Forward declarations
  468. template <bool, typename> class GenericArray;
  469. template <bool, typename> class GenericObject;
  470. ///////////////////////////////////////////////////////////////////////////////
  471. // GenericValue
  472. //! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
  473. /*!
  474. A JSON value can be one of 7 types. This class is a variant type supporting
  475. these types.
  476. Use the Value if UTF8 and default allocator
  477. \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
  478. \tparam Allocator Allocator type for allocating memory of object, array and string.
  479. */
  480. template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
  481. class GenericValue {
  482. public:
  483. //! Name-value pair in an object.
  484. typedef GenericMember<Encoding, Allocator> Member;
  485. typedef Encoding EncodingType; //!< Encoding type from template parameter.
  486. typedef Allocator AllocatorType; //!< Allocator type from template parameter.
  487. typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
  488. typedef GenericStringRef<Ch> StringRefType; //!< Reference to a constant string
  489. typedef typename GenericMemberIterator<false,Encoding,Allocator>::Iterator MemberIterator; //!< Member iterator for iterating in object.
  490. typedef typename GenericMemberIterator<true,Encoding,Allocator>::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object.
  491. typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
  492. typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
  493. typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of itself.
  494. typedef GenericArray<false, ValueType> Array;
  495. typedef GenericArray<true, ValueType> ConstArray;
  496. typedef GenericObject<false, ValueType> Object;
  497. typedef GenericObject<true, ValueType> ConstObject;
  498. //!@name Constructors and destructor.
  499. //@{
  500. //! Default constructor creates a null value.
  501. GenericValue() CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; }
  502. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  503. //! Move constructor in C++11
  504. GenericValue(GenericValue&& rhs) CEREAL_RAPIDJSON_NOEXCEPT : data_(rhs.data_) {
  505. rhs.data_.f.flags = kNullFlag; // give up contents
  506. }
  507. #endif
  508. private:
  509. //! Copy constructor is not permitted.
  510. GenericValue(const GenericValue& rhs);
  511. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  512. //! Moving from a GenericDocument is not permitted.
  513. template <typename StackAllocator>
  514. GenericValue(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs);
  515. //! Move assignment from a GenericDocument is not permitted.
  516. template <typename StackAllocator>
  517. GenericValue& operator=(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs);
  518. #endif
  519. public:
  520. //! Constructor with JSON value type.
  521. /*! This creates a Value of specified type with default content.
  522. \param type Type of the value.
  523. \note Default content for number is zero.
  524. */
  525. explicit GenericValue(Type type) CEREAL_RAPIDJSON_NOEXCEPT : data_() {
  526. static const uint16_t defaultFlags[] = {
  527. kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag,
  528. kNumberAnyFlag
  529. };
  530. CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(type >= kNullType && type <= kNumberType);
  531. data_.f.flags = defaultFlags[type];
  532. // Use ShortString to store empty string.
  533. if (type == kStringType)
  534. data_.ss.SetLength(0);
  535. }
  536. //! Explicit copy constructor (with allocator)
  537. /*! Creates a copy of a Value by using the given Allocator
  538. \tparam SourceAllocator allocator of \c rhs
  539. \param rhs Value to copy from (read-only)
  540. \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator().
  541. \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
  542. \see CopyFrom()
  543. */
  544. template <typename SourceAllocator>
  545. GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) {
  546. switch (rhs.GetType()) {
  547. case kObjectType: {
  548. SizeType count = rhs.data_.o.size;
  549. Member* lm = reinterpret_cast<Member*>(allocator.Malloc(count * sizeof(Member)));
  550. const typename GenericValue<Encoding,SourceAllocator>::Member* rm = rhs.GetMembersPointer();
  551. for (SizeType i = 0; i < count; i++) {
  552. new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings);
  553. new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings);
  554. }
  555. data_.f.flags = kObjectFlag;
  556. data_.o.size = data_.o.capacity = count;
  557. SetMembersPointer(lm);
  558. }
  559. break;
  560. case kArrayType: {
  561. SizeType count = rhs.data_.a.size;
  562. GenericValue* le = reinterpret_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue)));
  563. const GenericValue<Encoding,SourceAllocator>* re = rhs.GetElementsPointer();
  564. for (SizeType i = 0; i < count; i++)
  565. new (&le[i]) GenericValue(re[i], allocator, copyConstStrings);
  566. data_.f.flags = kArrayFlag;
  567. data_.a.size = data_.a.capacity = count;
  568. SetElementsPointer(le);
  569. }
  570. break;
  571. case kStringType:
  572. if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) {
  573. data_.f.flags = rhs.data_.f.flags;
  574. data_ = *reinterpret_cast<const Data*>(&rhs.data_);
  575. }
  576. else
  577. SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
  578. break;
  579. default:
  580. data_.f.flags = rhs.data_.f.flags;
  581. data_ = *reinterpret_cast<const Data*>(&rhs.data_);
  582. break;
  583. }
  584. }
  585. //! Constructor for boolean value.
  586. /*! \param b Boolean value
  587. \note This constructor is limited to \em real boolean values and rejects
  588. implicitly converted types like arbitrary pointers. Use an explicit cast
  589. to \c bool, if you want to construct a boolean JSON value in such cases.
  590. */
  591. #ifndef CEREAL_RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen
  592. template <typename T>
  593. explicit GenericValue(T b, CEREAL_RAPIDJSON_ENABLEIF((internal::IsSame<bool, T>))) CEREAL_RAPIDJSON_NOEXCEPT // See #472
  594. #else
  595. explicit GenericValue(bool b) CEREAL_RAPIDJSON_NOEXCEPT
  596. #endif
  597. : data_() {
  598. // safe-guard against failing SFINAE
  599. CEREAL_RAPIDJSON_STATIC_ASSERT((internal::IsSame<bool,T>::Value));
  600. data_.f.flags = b ? kTrueFlag : kFalseFlag;
  601. }
  602. //! Constructor for int value.
  603. explicit GenericValue(int i) CEREAL_RAPIDJSON_NOEXCEPT : data_() {
  604. data_.n.i64 = i;
  605. data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag;
  606. }
  607. //! Constructor for unsigned value.
  608. explicit GenericValue(unsigned u) CEREAL_RAPIDJSON_NOEXCEPT : data_() {
  609. data_.n.u64 = u;
  610. data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag);
  611. }
  612. //! Constructor for int64_t value.
  613. explicit GenericValue(int64_t i64) CEREAL_RAPIDJSON_NOEXCEPT : data_() {
  614. data_.n.i64 = i64;
  615. data_.f.flags = kNumberInt64Flag;
  616. if (i64 >= 0) {
  617. data_.f.flags |= kNumberUint64Flag;
  618. if (!(static_cast<uint64_t>(i64) & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
  619. data_.f.flags |= kUintFlag;
  620. if (!(static_cast<uint64_t>(i64) & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
  621. data_.f.flags |= kIntFlag;
  622. }
  623. else if (i64 >= static_cast<int64_t>(CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
  624. data_.f.flags |= kIntFlag;
  625. }
  626. //! Constructor for uint64_t value.
  627. explicit GenericValue(uint64_t u64) CEREAL_RAPIDJSON_NOEXCEPT : data_() {
  628. data_.n.u64 = u64;
  629. data_.f.flags = kNumberUint64Flag;
  630. if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0x80000000, 0x00000000)))
  631. data_.f.flags |= kInt64Flag;
  632. if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
  633. data_.f.flags |= kUintFlag;
  634. if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
  635. data_.f.flags |= kIntFlag;
  636. }
  637. //! Constructor for double value.
  638. explicit GenericValue(double d) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; }
  639. //! Constructor for float value.
  640. explicit GenericValue(float f) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast<double>(f); data_.f.flags = kNumberDoubleFlag; }
  641. //! Constructor for constant string (i.e. do not make a copy of string)
  642. GenericValue(const Ch* s, SizeType length) CEREAL_RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); }
  643. //! Constructor for constant string (i.e. do not make a copy of string)
  644. explicit GenericValue(StringRefType s) CEREAL_RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); }
  645. //! Constructor for copy-string (i.e. do make a copy of string)
  646. GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); }
  647. //! Constructor for copy-string (i.e. do make a copy of string)
  648. GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
  649. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  650. //! Constructor for copy-string from a string object (i.e. do make a copy of string)
  651. /*! \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING.
  652. */
  653. GenericValue(const std::basic_string<Ch>& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
  654. #endif
  655. //! Constructor for Array.
  656. /*!
  657. \param a An array obtained by \c GetArray().
  658. \note \c Array is always pass-by-value.
  659. \note the source array is moved into this value and the sourec array becomes empty.
  660. */
  661. GenericValue(Array a) CEREAL_RAPIDJSON_NOEXCEPT : data_(a.value_.data_) {
  662. a.value_.data_ = Data();
  663. a.value_.data_.f.flags = kArrayFlag;
  664. }
  665. //! Constructor for Object.
  666. /*!
  667. \param o An object obtained by \c GetObject().
  668. \note \c Object is always pass-by-value.
  669. \note the source object is moved into this value and the sourec object becomes empty.
  670. */
  671. GenericValue(Object o) CEREAL_RAPIDJSON_NOEXCEPT : data_(o.value_.data_) {
  672. o.value_.data_ = Data();
  673. o.value_.data_.f.flags = kObjectFlag;
  674. }
  675. //! Destructor.
  676. /*! Need to destruct elements of array, members of object, or copy-string.
  677. */
  678. ~GenericValue() {
  679. if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
  680. switch(data_.f.flags) {
  681. case kArrayFlag:
  682. {
  683. GenericValue* e = GetElementsPointer();
  684. for (GenericValue* v = e; v != e + data_.a.size; ++v)
  685. v->~GenericValue();
  686. Allocator::Free(e);
  687. }
  688. break;
  689. case kObjectFlag:
  690. for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
  691. m->~Member();
  692. Allocator::Free(GetMembersPointer());
  693. break;
  694. case kCopyStringFlag:
  695. Allocator::Free(const_cast<Ch*>(GetStringPointer()));
  696. break;
  697. default:
  698. break; // Do nothing for other types.
  699. }
  700. }
  701. }
  702. //@}
  703. //!@name Assignment operators
  704. //@{
  705. //! Assignment with move semantics.
  706. /*! \param rhs Source of the assignment. It will become a null value after assignment.
  707. */
  708. GenericValue& operator=(GenericValue& rhs) CEREAL_RAPIDJSON_NOEXCEPT {
  709. if (CEREAL_RAPIDJSON_LIKELY(this != &rhs)) {
  710. this->~GenericValue();
  711. RawAssign(rhs);
  712. }
  713. return *this;
  714. }
  715. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  716. //! Move assignment in C++11
  717. GenericValue& operator=(GenericValue&& rhs) CEREAL_RAPIDJSON_NOEXCEPT {
  718. return *this = rhs.Move();
  719. }
  720. #endif
  721. //! Assignment of constant string reference (no copy)
  722. /*! \param str Constant string reference to be assigned
  723. \note This overload is needed to avoid clashes with the generic primitive type assignment overload below.
  724. \see GenericStringRef, operator=(T)
  725. */
  726. GenericValue& operator=(StringRefType str) CEREAL_RAPIDJSON_NOEXCEPT {
  727. GenericValue s(str);
  728. return *this = s;
  729. }
  730. //! Assignment with primitive types.
  731. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
  732. \param value The value to be assigned.
  733. \note The source type \c T explicitly disallows all pointer types,
  734. especially (\c const) \ref Ch*. This helps avoiding implicitly
  735. referencing character strings with insufficient lifetime, use
  736. \ref SetString(const Ch*, Allocator&) (for copying) or
  737. \ref StringRef() (to explicitly mark the pointer as constant) instead.
  738. All other pointer types would implicitly convert to \c bool,
  739. use \ref SetBool() instead.
  740. */
  741. template <typename T>
  742. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer<T>), (GenericValue&))
  743. operator=(T value) {
  744. GenericValue v(value);
  745. return *this = v;
  746. }
  747. //! Deep-copy assignment from Value
  748. /*! Assigns a \b copy of the Value to the current Value object
  749. \tparam SourceAllocator Allocator type of \c rhs
  750. \param rhs Value to copy from (read-only)
  751. \param allocator Allocator to use for copying
  752. \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
  753. */
  754. template <typename SourceAllocator>
  755. GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) {
  756. CEREAL_RAPIDJSON_ASSERT(static_cast<void*>(this) != static_cast<void const*>(&rhs));
  757. this->~GenericValue();
  758. new (this) GenericValue(rhs, allocator, copyConstStrings);
  759. return *this;
  760. }
  761. //! Exchange the contents of this value with those of other.
  762. /*!
  763. \param other Another value.
  764. \note Constant complexity.
  765. */
  766. GenericValue& Swap(GenericValue& other) CEREAL_RAPIDJSON_NOEXCEPT {
  767. GenericValue temp;
  768. temp.RawAssign(*this);
  769. RawAssign(other);
  770. other.RawAssign(temp);
  771. return *this;
  772. }
  773. //! free-standing swap function helper
  774. /*!
  775. Helper function to enable support for common swap implementation pattern based on \c std::swap:
  776. \code
  777. void swap(MyClass& a, MyClass& b) {
  778. using std::swap;
  779. swap(a.value, b.value);
  780. // ...
  781. }
  782. \endcode
  783. \see Swap()
  784. */
  785. friend inline void swap(GenericValue& a, GenericValue& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); }
  786. //! Prepare Value for move semantics
  787. /*! \return *this */
  788. GenericValue& Move() CEREAL_RAPIDJSON_NOEXCEPT { return *this; }
  789. //@}
  790. //!@name Equal-to and not-equal-to operators
  791. //@{
  792. //! Equal-to operator
  793. /*!
  794. \note If an object contains duplicated named member, comparing equality with any object is always \c false.
  795. \note Complexity is quadratic in Object's member number and linear for the rest (number of all values in the subtree and total lengths of all strings).
  796. */
  797. template <typename SourceAllocator>
  798. bool operator==(const GenericValue<Encoding, SourceAllocator>& rhs) const {
  799. typedef GenericValue<Encoding, SourceAllocator> RhsType;
  800. if (GetType() != rhs.GetType())
  801. return false;
  802. switch (GetType()) {
  803. case kObjectType: // Warning: O(n^2) inner-loop
  804. if (data_.o.size != rhs.data_.o.size)
  805. return false;
  806. for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) {
  807. typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name);
  808. if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value)
  809. return false;
  810. }
  811. return true;
  812. case kArrayType:
  813. if (data_.a.size != rhs.data_.a.size)
  814. return false;
  815. for (SizeType i = 0; i < data_.a.size; i++)
  816. if ((*this)[i] != rhs[i])
  817. return false;
  818. return true;
  819. case kStringType:
  820. return StringEqual(rhs);
  821. case kNumberType:
  822. if (IsDouble() || rhs.IsDouble()) {
  823. double a = GetDouble(); // May convert from integer to double.
  824. double b = rhs.GetDouble(); // Ditto
  825. return a >= b && a <= b; // Prevent -Wfloat-equal
  826. }
  827. else
  828. return data_.n.u64 == rhs.data_.n.u64;
  829. default:
  830. return true;
  831. }
  832. }
  833. //! Equal-to operator with const C-string pointer
  834. bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); }
  835. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  836. //! Equal-to operator with string object
  837. /*! \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING.
  838. */
  839. bool operator==(const std::basic_string<Ch>& rhs) const { return *this == GenericValue(StringRef(rhs)); }
  840. #endif
  841. //! Equal-to operator with primitive types
  842. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false
  843. */
  844. template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>,internal::IsGenericValue<T> >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); }
  845. //! Not-equal-to operator
  846. /*! \return !(*this == rhs)
  847. */
  848. template <typename SourceAllocator>
  849. bool operator!=(const GenericValue<Encoding, SourceAllocator>& rhs) const { return !(*this == rhs); }
  850. //! Not-equal-to operator with const C-string pointer
  851. bool operator!=(const Ch* rhs) const { return !(*this == rhs); }
  852. //! Not-equal-to operator with arbitrary types
  853. /*! \return !(*this == rhs)
  854. */
  855. template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); }
  856. //! Equal-to operator with arbitrary types (symmetric version)
  857. /*! \return (rhs == lhs)
  858. */
  859. template <typename T> friend CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; }
  860. //! Not-Equal-to operator with arbitrary types (symmetric version)
  861. /*! \return !(rhs == lhs)
  862. */
  863. template <typename T> friend CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); }
  864. //@}
  865. //!@name Type
  866. //@{
  867. Type GetType() const { return static_cast<Type>(data_.f.flags & kTypeMask); }
  868. bool IsNull() const { return data_.f.flags == kNullFlag; }
  869. bool IsFalse() const { return data_.f.flags == kFalseFlag; }
  870. bool IsTrue() const { return data_.f.flags == kTrueFlag; }
  871. bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; }
  872. bool IsObject() const { return data_.f.flags == kObjectFlag; }
  873. bool IsArray() const { return data_.f.flags == kArrayFlag; }
  874. bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; }
  875. bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; }
  876. bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; }
  877. bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; }
  878. bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; }
  879. bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; }
  880. bool IsString() const { return (data_.f.flags & kStringFlag) != 0; }
  881. // Checks whether a number can be losslessly converted to a double.
  882. bool IsLosslessDouble() const {
  883. if (!IsNumber()) return false;
  884. if (IsUint64()) {
  885. uint64_t u = GetUint64();
  886. volatile double d = static_cast<double>(u);
  887. return (d >= 0.0)
  888. && (d < static_cast<double>((std::numeric_limits<uint64_t>::max)()))
  889. && (u == static_cast<uint64_t>(d));
  890. }
  891. if (IsInt64()) {
  892. int64_t i = GetInt64();
  893. volatile double d = static_cast<double>(i);
  894. return (d >= static_cast<double>((std::numeric_limits<int64_t>::min)()))
  895. && (d < static_cast<double>((std::numeric_limits<int64_t>::max)()))
  896. && (i == static_cast<int64_t>(d));
  897. }
  898. return true; // double, int, uint are always lossless
  899. }
  900. // Checks whether a number is a float (possible lossy).
  901. bool IsFloat() const {
  902. if ((data_.f.flags & kDoubleFlag) == 0)
  903. return false;
  904. double d = GetDouble();
  905. return d >= -3.4028234e38 && d <= 3.4028234e38;
  906. }
  907. // Checks whether a number can be losslessly converted to a float.
  908. bool IsLosslessFloat() const {
  909. if (!IsNumber()) return false;
  910. double a = GetDouble();
  911. if (a < static_cast<double>(-(std::numeric_limits<float>::max)())
  912. || a > static_cast<double>((std::numeric_limits<float>::max)()))
  913. return false;
  914. double b = static_cast<double>(static_cast<float>(a));
  915. return a >= b && a <= b; // Prevent -Wfloat-equal
  916. }
  917. //@}
  918. //!@name Null
  919. //@{
  920. GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
  921. //@}
  922. //!@name Bool
  923. //@{
  924. bool GetBool() const { CEREAL_RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; }
  925. //!< Set boolean value
  926. /*! \post IsBool() == true */
  927. GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
  928. //@}
  929. //!@name Object
  930. //@{
  931. //! Set this value as an empty object.
  932. /*! \post IsObject() == true */
  933. GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
  934. //! Get the number of members in the object.
  935. SizeType MemberCount() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size; }
  936. //! Get the capacity of object.
  937. SizeType MemberCapacity() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; }
  938. //! Check whether the object is empty.
  939. bool ObjectEmpty() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; }
  940. //! Get a value from an object associated with the name.
  941. /*! \pre IsObject() == true
  942. \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType))
  943. \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
  944. Since 0.2, if the name is not correct, it will assert.
  945. If user is unsure whether a member exists, user should use HasMember() first.
  946. A better approach is to use FindMember().
  947. \note Linear time complexity.
  948. */
  949. template <typename T>
  950. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(GenericValue&)) operator[](T* name) {
  951. GenericValue n(StringRef(name));
  952. return (*this)[n];
  953. }
  954. template <typename T>
  955. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast<GenericValue&>(*this)[name]; }
  956. //! Get a value from an object associated with the name.
  957. /*! \pre IsObject() == true
  958. \tparam SourceAllocator Allocator of the \c name value
  959. \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen().
  960. And it can also handle strings with embedded null characters.
  961. \note Linear time complexity.
  962. */
  963. template <typename SourceAllocator>
  964. GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) {
  965. MemberIterator member = FindMember(name);
  966. if (member != MemberEnd())
  967. return member->value;
  968. else {
  969. CEREAL_RAPIDJSON_ASSERT(false); // see above note
  970. // This will generate -Wexit-time-destructors in clang
  971. // static GenericValue NullValue;
  972. // return NullValue;
  973. // Use static buffer and placement-new to prevent destruction
  974. static char buffer[sizeof(GenericValue)];
  975. return *new (buffer) GenericValue();
  976. }
  977. }
  978. template <typename SourceAllocator>
  979. const GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this)[name]; }
  980. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  981. //! Get a value from an object associated with name (string object).
  982. GenericValue& operator[](const std::basic_string<Ch>& name) { return (*this)[GenericValue(StringRef(name))]; }
  983. const GenericValue& operator[](const std::basic_string<Ch>& name) const { return (*this)[GenericValue(StringRef(name))]; }
  984. #endif
  985. //! Const member iterator
  986. /*! \pre IsObject() == true */
  987. ConstMemberIterator MemberBegin() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); }
  988. //! Const \em past-the-end member iterator
  989. /*! \pre IsObject() == true */
  990. ConstMemberIterator MemberEnd() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); }
  991. //! Member iterator
  992. /*! \pre IsObject() == true */
  993. MemberIterator MemberBegin() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); }
  994. //! \em Past-the-end member iterator
  995. /*! \pre IsObject() == true */
  996. MemberIterator MemberEnd() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); }
  997. //! Request the object to have enough capacity to store members.
  998. /*! \param newCapacity The capacity that the object at least need to have.
  999. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1000. \return The value itself for fluent API.
  1001. \note Linear time complexity.
  1002. */
  1003. GenericValue& MemberReserve(SizeType newCapacity, Allocator &allocator) {
  1004. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1005. if (newCapacity > data_.o.capacity) {
  1006. SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member))));
  1007. data_.o.capacity = newCapacity;
  1008. }
  1009. return *this;
  1010. }
  1011. //! Check whether a member exists in the object.
  1012. /*!
  1013. \param name Member name to be searched.
  1014. \pre IsObject() == true
  1015. \return Whether a member with that name exists.
  1016. \note It is better to use FindMember() directly if you need the obtain the value as well.
  1017. \note Linear time complexity.
  1018. */
  1019. bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); }
  1020. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1021. //! Check whether a member exists in the object with string object.
  1022. /*!
  1023. \param name Member name to be searched.
  1024. \pre IsObject() == true
  1025. \return Whether a member with that name exists.
  1026. \note It is better to use FindMember() directly if you need the obtain the value as well.
  1027. \note Linear time complexity.
  1028. */
  1029. bool HasMember(const std::basic_string<Ch>& name) const { return FindMember(name) != MemberEnd(); }
  1030. #endif
  1031. //! Check whether a member exists in the object with GenericValue name.
  1032. /*!
  1033. This version is faster because it does not need a StrLen(). It can also handle string with null character.
  1034. \param name Member name to be searched.
  1035. \pre IsObject() == true
  1036. \return Whether a member with that name exists.
  1037. \note It is better to use FindMember() directly if you need the obtain the value as well.
  1038. \note Linear time complexity.
  1039. */
  1040. template <typename SourceAllocator>
  1041. bool HasMember(const GenericValue<Encoding, SourceAllocator>& name) const { return FindMember(name) != MemberEnd(); }
  1042. //! Find member by name.
  1043. /*!
  1044. \param name Member name to be searched.
  1045. \pre IsObject() == true
  1046. \return Iterator to member, if it exists.
  1047. Otherwise returns \ref MemberEnd().
  1048. \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
  1049. the requested member doesn't exist. For consistency with e.g.
  1050. \c std::map, this has been changed to MemberEnd() now.
  1051. \note Linear time complexity.
  1052. */
  1053. MemberIterator FindMember(const Ch* name) {
  1054. GenericValue n(StringRef(name));
  1055. return FindMember(n);
  1056. }
  1057. ConstMemberIterator FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
  1058. //! Find member by name.
  1059. /*!
  1060. This version is faster because it does not need a StrLen(). It can also handle string with null character.
  1061. \param name Member name to be searched.
  1062. \pre IsObject() == true
  1063. \return Iterator to member, if it exists.
  1064. Otherwise returns \ref MemberEnd().
  1065. \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
  1066. the requested member doesn't exist. For consistency with e.g.
  1067. \c std::map, this has been changed to MemberEnd() now.
  1068. \note Linear time complexity.
  1069. */
  1070. template <typename SourceAllocator>
  1071. MemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) {
  1072. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1073. CEREAL_RAPIDJSON_ASSERT(name.IsString());
  1074. MemberIterator member = MemberBegin();
  1075. for ( ; member != MemberEnd(); ++member)
  1076. if (name.StringEqual(member->name))
  1077. break;
  1078. return member;
  1079. }
  1080. template <typename SourceAllocator> ConstMemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
  1081. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1082. //! Find member by string object name.
  1083. /*!
  1084. \param name Member name to be searched.
  1085. \pre IsObject() == true
  1086. \return Iterator to member, if it exists.
  1087. Otherwise returns \ref MemberEnd().
  1088. */
  1089. MemberIterator FindMember(const std::basic_string<Ch>& name) { return FindMember(GenericValue(StringRef(name))); }
  1090. ConstMemberIterator FindMember(const std::basic_string<Ch>& name) const { return FindMember(GenericValue(StringRef(name))); }
  1091. #endif
  1092. //! Add a member (name-value pair) to the object.
  1093. /*! \param name A string value as name of member.
  1094. \param value Value of any type.
  1095. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1096. \return The value itself for fluent API.
  1097. \note The ownership of \c name and \c value will be transferred to this object on success.
  1098. \pre IsObject() && name.IsString()
  1099. \post name.IsNull() && value.IsNull()
  1100. \note Amortized Constant time complexity.
  1101. */
  1102. GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
  1103. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1104. CEREAL_RAPIDJSON_ASSERT(name.IsString());
  1105. ObjectData& o = data_.o;
  1106. if (o.size >= o.capacity)
  1107. MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator);
  1108. Member* members = GetMembersPointer();
  1109. members[o.size].name.RawAssign(name);
  1110. members[o.size].value.RawAssign(value);
  1111. o.size++;
  1112. return *this;
  1113. }
  1114. //! Add a constant string value as member (name-value pair) to the object.
  1115. /*! \param name A string value as name of member.
  1116. \param value constant string reference as value of member.
  1117. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1118. \return The value itself for fluent API.
  1119. \pre IsObject()
  1120. \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
  1121. \note Amortized Constant time complexity.
  1122. */
  1123. GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) {
  1124. GenericValue v(value);
  1125. return AddMember(name, v, allocator);
  1126. }
  1127. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1128. //! Add a string object as member (name-value pair) to the object.
  1129. /*! \param name A string value as name of member.
  1130. \param value constant string reference as value of member.
  1131. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1132. \return The value itself for fluent API.
  1133. \pre IsObject()
  1134. \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
  1135. \note Amortized Constant time complexity.
  1136. */
  1137. GenericValue& AddMember(GenericValue& name, std::basic_string<Ch>& value, Allocator& allocator) {
  1138. GenericValue v(value, allocator);
  1139. return AddMember(name, v, allocator);
  1140. }
  1141. #endif
  1142. //! Add any primitive value as member (name-value pair) to the object.
  1143. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
  1144. \param name A string value as name of member.
  1145. \param value Value of primitive type \c T as value of member
  1146. \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
  1147. \return The value itself for fluent API.
  1148. \pre IsObject()
  1149. \note The source type \c T explicitly disallows all pointer types,
  1150. especially (\c const) \ref Ch*. This helps avoiding implicitly
  1151. referencing character strings with insufficient lifetime, use
  1152. \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
  1153. AddMember(StringRefType, StringRefType, Allocator&).
  1154. All other pointer types would implicitly convert to \c bool,
  1155. use an explicit cast instead, if needed.
  1156. \note Amortized Constant time complexity.
  1157. */
  1158. template <typename T>
  1159. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
  1160. AddMember(GenericValue& name, T value, Allocator& allocator) {
  1161. GenericValue v(value);
  1162. return AddMember(name, v, allocator);
  1163. }
  1164. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1165. GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) {
  1166. return AddMember(name, value, allocator);
  1167. }
  1168. GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) {
  1169. return AddMember(name, value, allocator);
  1170. }
  1171. GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) {
  1172. return AddMember(name, value, allocator);
  1173. }
  1174. GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) {
  1175. GenericValue n(name);
  1176. return AddMember(n, value, allocator);
  1177. }
  1178. #endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1179. //! Add a member (name-value pair) to the object.
  1180. /*! \param name A constant string reference as name of member.
  1181. \param value Value of any type.
  1182. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1183. \return The value itself for fluent API.
  1184. \note The ownership of \c value will be transferred to this object on success.
  1185. \pre IsObject()
  1186. \post value.IsNull()
  1187. \note Amortized Constant time complexity.
  1188. */
  1189. GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) {
  1190. GenericValue n(name);
  1191. return AddMember(n, value, allocator);
  1192. }
  1193. //! Add a constant string value as member (name-value pair) to the object.
  1194. /*! \param name A constant string reference as name of member.
  1195. \param value constant string reference as value of member.
  1196. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1197. \return The value itself for fluent API.
  1198. \pre IsObject()
  1199. \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below.
  1200. \note Amortized Constant time complexity.
  1201. */
  1202. GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) {
  1203. GenericValue v(value);
  1204. return AddMember(name, v, allocator);
  1205. }
  1206. //! Add any primitive value as member (name-value pair) to the object.
  1207. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
  1208. \param name A constant string reference as name of member.
  1209. \param value Value of primitive type \c T as value of member
  1210. \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
  1211. \return The value itself for fluent API.
  1212. \pre IsObject()
  1213. \note The source type \c T explicitly disallows all pointer types,
  1214. especially (\c const) \ref Ch*. This helps avoiding implicitly
  1215. referencing character strings with insufficient lifetime, use
  1216. \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
  1217. AddMember(StringRefType, StringRefType, Allocator&).
  1218. All other pointer types would implicitly convert to \c bool,
  1219. use an explicit cast instead, if needed.
  1220. \note Amortized Constant time complexity.
  1221. */
  1222. template <typename T>
  1223. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
  1224. AddMember(StringRefType name, T value, Allocator& allocator) {
  1225. GenericValue n(name);
  1226. return AddMember(n, value, allocator);
  1227. }
  1228. //! Remove all members in the object.
  1229. /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged.
  1230. \note Linear time complexity.
  1231. */
  1232. void RemoveAllMembers() {
  1233. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1234. for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
  1235. m->~Member();
  1236. data_.o.size = 0;
  1237. }
  1238. //! Remove a member in object by its name.
  1239. /*! \param name Name of member to be removed.
  1240. \return Whether the member existed.
  1241. \note This function may reorder the object members. Use \ref
  1242. EraseMember(ConstMemberIterator) if you need to preserve the
  1243. relative order of the remaining members.
  1244. \note Linear time complexity.
  1245. */
  1246. bool RemoveMember(const Ch* name) {
  1247. GenericValue n(StringRef(name));
  1248. return RemoveMember(n);
  1249. }
  1250. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1251. bool RemoveMember(const std::basic_string<Ch>& name) { return RemoveMember(GenericValue(StringRef(name))); }
  1252. #endif
  1253. template <typename SourceAllocator>
  1254. bool RemoveMember(const GenericValue<Encoding, SourceAllocator>& name) {
  1255. MemberIterator m = FindMember(name);
  1256. if (m != MemberEnd()) {
  1257. RemoveMember(m);
  1258. return true;
  1259. }
  1260. else
  1261. return false;
  1262. }
  1263. //! Remove a member in object by iterator.
  1264. /*! \param m member iterator (obtained by FindMember() or MemberBegin()).
  1265. \return the new iterator after removal.
  1266. \note This function may reorder the object members. Use \ref
  1267. EraseMember(ConstMemberIterator) if you need to preserve the
  1268. relative order of the remaining members.
  1269. \note Constant time complexity.
  1270. */
  1271. MemberIterator RemoveMember(MemberIterator m) {
  1272. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1273. CEREAL_RAPIDJSON_ASSERT(data_.o.size > 0);
  1274. CEREAL_RAPIDJSON_ASSERT(GetMembersPointer() != 0);
  1275. CEREAL_RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd());
  1276. MemberIterator last(GetMembersPointer() + (data_.o.size - 1));
  1277. if (data_.o.size > 1 && m != last)
  1278. *m = *last; // Move the last one to this place
  1279. else
  1280. m->~Member(); // Only one left, just destroy
  1281. --data_.o.size;
  1282. return m;
  1283. }
  1284. //! Remove a member from an object by iterator.
  1285. /*! \param pos iterator to the member to remove
  1286. \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd()
  1287. \return Iterator following the removed element.
  1288. If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned.
  1289. \note This function preserves the relative order of the remaining object
  1290. members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator).
  1291. \note Linear time complexity.
  1292. */
  1293. MemberIterator EraseMember(ConstMemberIterator pos) {
  1294. return EraseMember(pos, pos +1);
  1295. }
  1296. //! Remove members in the range [first, last) from an object.
  1297. /*! \param first iterator to the first member to remove
  1298. \param last iterator following the last member to remove
  1299. \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd()
  1300. \return Iterator following the last removed element.
  1301. \note This function preserves the relative order of the remaining object
  1302. members.
  1303. \note Linear time complexity.
  1304. */
  1305. MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) {
  1306. CEREAL_RAPIDJSON_ASSERT(IsObject());
  1307. CEREAL_RAPIDJSON_ASSERT(data_.o.size > 0);
  1308. CEREAL_RAPIDJSON_ASSERT(GetMembersPointer() != 0);
  1309. CEREAL_RAPIDJSON_ASSERT(first >= MemberBegin());
  1310. CEREAL_RAPIDJSON_ASSERT(first <= last);
  1311. CEREAL_RAPIDJSON_ASSERT(last <= MemberEnd());
  1312. MemberIterator pos = MemberBegin() + (first - MemberBegin());
  1313. for (MemberIterator itr = pos; itr != last; ++itr)
  1314. itr->~Member();
  1315. std::memmove(static_cast<void*>(&*pos), &*last, static_cast<size_t>(MemberEnd() - last) * sizeof(Member));
  1316. data_.o.size -= static_cast<SizeType>(last - first);
  1317. return pos;
  1318. }
  1319. //! Erase a member in object by its name.
  1320. /*! \param name Name of member to be removed.
  1321. \return Whether the member existed.
  1322. \note Linear time complexity.
  1323. */
  1324. bool EraseMember(const Ch* name) {
  1325. GenericValue n(StringRef(name));
  1326. return EraseMember(n);
  1327. }
  1328. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1329. bool EraseMember(const std::basic_string<Ch>& name) { return EraseMember(GenericValue(StringRef(name))); }
  1330. #endif
  1331. template <typename SourceAllocator>
  1332. bool EraseMember(const GenericValue<Encoding, SourceAllocator>& name) {
  1333. MemberIterator m = FindMember(name);
  1334. if (m != MemberEnd()) {
  1335. EraseMember(m);
  1336. return true;
  1337. }
  1338. else
  1339. return false;
  1340. }
  1341. Object GetObject() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return Object(*this); }
  1342. ConstObject GetObject() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); }
  1343. //@}
  1344. //!@name Array
  1345. //@{
  1346. //! Set this value as an empty array.
  1347. /*! \post IsArray == true */
  1348. GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
  1349. //! Get the number of elements in array.
  1350. SizeType Size() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
  1351. //! Get the capacity of array.
  1352. SizeType Capacity() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
  1353. //! Check whether the array is empty.
  1354. bool Empty() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
  1355. //! Remove all elements in the array.
  1356. /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
  1357. \note Linear time complexity.
  1358. */
  1359. void Clear() {
  1360. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1361. GenericValue* e = GetElementsPointer();
  1362. for (GenericValue* v = e; v != e + data_.a.size; ++v)
  1363. v->~GenericValue();
  1364. data_.a.size = 0;
  1365. }
  1366. //! Get an element from array by index.
  1367. /*! \pre IsArray() == true
  1368. \param index Zero-based index of element.
  1369. \see operator[](T*)
  1370. */
  1371. GenericValue& operator[](SizeType index) {
  1372. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1373. CEREAL_RAPIDJSON_ASSERT(index < data_.a.size);
  1374. return GetElementsPointer()[index];
  1375. }
  1376. const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; }
  1377. //! Element iterator
  1378. /*! \pre IsArray() == true */
  1379. ValueIterator Begin() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); }
  1380. //! \em Past-the-end element iterator
  1381. /*! \pre IsArray() == true */
  1382. ValueIterator End() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; }
  1383. //! Constant element iterator
  1384. /*! \pre IsArray() == true */
  1385. ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); }
  1386. //! Constant \em past-the-end element iterator
  1387. /*! \pre IsArray() == true */
  1388. ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); }
  1389. //! Request the array to have enough capacity to store elements.
  1390. /*! \param newCapacity The capacity that the array at least need to have.
  1391. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1392. \return The value itself for fluent API.
  1393. \note Linear time complexity.
  1394. */
  1395. GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
  1396. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1397. if (newCapacity > data_.a.capacity) {
  1398. SetElementsPointer(reinterpret_cast<GenericValue*>(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue))));
  1399. data_.a.capacity = newCapacity;
  1400. }
  1401. return *this;
  1402. }
  1403. //! Append a GenericValue at the end of the array.
  1404. /*! \param value Value to be appended.
  1405. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1406. \pre IsArray() == true
  1407. \post value.IsNull() == true
  1408. \return The value itself for fluent API.
  1409. \note The ownership of \c value will be transferred to this array on success.
  1410. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
  1411. \note Amortized constant time complexity.
  1412. */
  1413. GenericValue& PushBack(GenericValue& value, Allocator& allocator) {
  1414. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1415. if (data_.a.size >= data_.a.capacity)
  1416. Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator);
  1417. GetElementsPointer()[data_.a.size++].RawAssign(value);
  1418. return *this;
  1419. }
  1420. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1421. GenericValue& PushBack(GenericValue&& value, Allocator& allocator) {
  1422. return PushBack(value, allocator);
  1423. }
  1424. #endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1425. //! Append a constant string reference at the end of the array.
  1426. /*! \param value Constant string reference to be appended.
  1427. \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator().
  1428. \pre IsArray() == true
  1429. \return The value itself for fluent API.
  1430. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
  1431. \note Amortized constant time complexity.
  1432. \see GenericStringRef
  1433. */
  1434. GenericValue& PushBack(StringRefType value, Allocator& allocator) {
  1435. return (*this).template PushBack<StringRefType>(value, allocator);
  1436. }
  1437. //! Append a primitive value at the end of the array.
  1438. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
  1439. \param value Value of primitive type T to be appended.
  1440. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
  1441. \pre IsArray() == true
  1442. \return The value itself for fluent API.
  1443. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
  1444. \note The source type \c T explicitly disallows all pointer types,
  1445. especially (\c const) \ref Ch*. This helps avoiding implicitly
  1446. referencing character strings with insufficient lifetime, use
  1447. \ref PushBack(GenericValue&, Allocator&) or \ref
  1448. PushBack(StringRefType, Allocator&).
  1449. All other pointer types would implicitly convert to \c bool,
  1450. use an explicit cast instead, if needed.
  1451. \note Amortized constant time complexity.
  1452. */
  1453. template <typename T>
  1454. CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
  1455. PushBack(T value, Allocator& allocator) {
  1456. GenericValue v(value);
  1457. return PushBack(v, allocator);
  1458. }
  1459. //! Remove the last element in the array.
  1460. /*!
  1461. \note Constant time complexity.
  1462. */
  1463. GenericValue& PopBack() {
  1464. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1465. CEREAL_RAPIDJSON_ASSERT(!Empty());
  1466. GetElementsPointer()[--data_.a.size].~GenericValue();
  1467. return *this;
  1468. }
  1469. //! Remove an element of array by iterator.
  1470. /*!
  1471. \param pos iterator to the element to remove
  1472. \pre IsArray() == true && \ref Begin() <= \c pos < \ref End()
  1473. \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned.
  1474. \note Linear time complexity.
  1475. */
  1476. ValueIterator Erase(ConstValueIterator pos) {
  1477. return Erase(pos, pos + 1);
  1478. }
  1479. //! Remove elements in the range [first, last) of the array.
  1480. /*!
  1481. \param first iterator to the first element to remove
  1482. \param last iterator following the last element to remove
  1483. \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End()
  1484. \return Iterator following the last removed element.
  1485. \note Linear time complexity.
  1486. */
  1487. ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) {
  1488. CEREAL_RAPIDJSON_ASSERT(IsArray());
  1489. CEREAL_RAPIDJSON_ASSERT(data_.a.size > 0);
  1490. CEREAL_RAPIDJSON_ASSERT(GetElementsPointer() != 0);
  1491. CEREAL_RAPIDJSON_ASSERT(first >= Begin());
  1492. CEREAL_RAPIDJSON_ASSERT(first <= last);
  1493. CEREAL_RAPIDJSON_ASSERT(last <= End());
  1494. ValueIterator pos = Begin() + (first - Begin());
  1495. for (ValueIterator itr = pos; itr != last; ++itr)
  1496. itr->~GenericValue();
  1497. std::memmove(static_cast<void*>(pos), last, static_cast<size_t>(End() - last) * sizeof(GenericValue));
  1498. data_.a.size -= static_cast<SizeType>(last - first);
  1499. return pos;
  1500. }
  1501. Array GetArray() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return Array(*this); }
  1502. ConstArray GetArray() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); }
  1503. //@}
  1504. //!@name Number
  1505. //@{
  1506. int GetInt() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; }
  1507. unsigned GetUint() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; }
  1508. int64_t GetInt64() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; }
  1509. uint64_t GetUint64() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; }
  1510. //! Get the value as double type.
  1511. /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless.
  1512. */
  1513. double GetDouble() const {
  1514. CEREAL_RAPIDJSON_ASSERT(IsNumber());
  1515. if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
  1516. if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double
  1517. if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
  1518. if ((data_.f.flags & kInt64Flag) != 0) return static_cast<double>(data_.n.i64); // int64_t -> double (may lose precision)
  1519. CEREAL_RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast<double>(data_.n.u64); // uint64_t -> double (may lose precision)
  1520. }
  1521. //! Get the value as float type.
  1522. /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless.
  1523. */
  1524. float GetFloat() const {
  1525. return static_cast<float>(GetDouble());
  1526. }
  1527. GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
  1528. GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
  1529. GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
  1530. GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
  1531. GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
  1532. GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast<double>(f)); return *this; }
  1533. //@}
  1534. //!@name String
  1535. //@{
  1536. const Ch* GetString() const { CEREAL_RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); }
  1537. //! Get the length of string.
  1538. /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
  1539. */
  1540. SizeType GetStringLength() const { CEREAL_RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); }
  1541. //! Set this value as a string without copying source string.
  1542. /*! This version has better performance with supplied length, and also support string containing null character.
  1543. \param s source string pointer.
  1544. \param length The length of source string, excluding the trailing null terminator.
  1545. \return The value itself for fluent API.
  1546. \post IsString() == true && GetString() == s && GetStringLength() == length
  1547. \see SetString(StringRefType)
  1548. */
  1549. GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); }
  1550. //! Set this value as a string without copying source string.
  1551. /*! \param s source string reference
  1552. \return The value itself for fluent API.
  1553. \post IsString() == true && GetString() == s && GetStringLength() == s.length
  1554. */
  1555. GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; }
  1556. //! Set this value as a string by copying from source string.
  1557. /*! This version has better performance with supplied length, and also support string containing null character.
  1558. \param s source string.
  1559. \param length The length of source string, excluding the trailing null terminator.
  1560. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
  1561. \return The value itself for fluent API.
  1562. \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
  1563. */
  1564. GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); }
  1565. //! Set this value as a string by copying from source string.
  1566. /*! \param s source string.
  1567. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
  1568. \return The value itself for fluent API.
  1569. \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
  1570. */
  1571. GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
  1572. //! Set this value as a string by copying from source string.
  1573. /*! \param s source string reference
  1574. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
  1575. \return The value itself for fluent API.
  1576. \post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length
  1577. */
  1578. GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; }
  1579. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  1580. //! Set this value as a string by copying from source string.
  1581. /*! \param s source string.
  1582. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
  1583. \return The value itself for fluent API.
  1584. \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size()
  1585. \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING.
  1586. */
  1587. GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
  1588. #endif
  1589. //@}
  1590. //!@name Array
  1591. //@{
  1592. //! Templated version for checking whether this value is type T.
  1593. /*!
  1594. \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string<Ch>
  1595. */
  1596. template <typename T>
  1597. bool Is() const { return internal::TypeHelper<ValueType, T>::Is(*this); }
  1598. template <typename T>
  1599. T Get() const { return internal::TypeHelper<ValueType, T>::Get(*this); }
  1600. template <typename T>
  1601. T Get() { return internal::TypeHelper<ValueType, T>::Get(*this); }
  1602. template<typename T>
  1603. ValueType& Set(const T& data) { return internal::TypeHelper<ValueType, T>::Set(*this, data); }
  1604. template<typename T>
  1605. ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper<ValueType, T>::Set(*this, data, allocator); }
  1606. //@}
  1607. //! Generate events of this value to a Handler.
  1608. /*! This function adopts the GoF visitor pattern.
  1609. Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
  1610. It can also be used to deep clone this value via GenericDocument, which is also a Handler.
  1611. \tparam Handler type of handler.
  1612. \param handler An object implementing concept Handler.
  1613. */
  1614. template <typename Handler>
  1615. bool Accept(Handler& handler) const {
  1616. switch(GetType()) {
  1617. case kNullType: return handler.Null();
  1618. case kFalseType: return handler.Bool(false);
  1619. case kTrueType: return handler.Bool(true);
  1620. case kObjectType:
  1621. if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartObject()))
  1622. return false;
  1623. for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
  1624. CEREAL_RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator.
  1625. if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0)))
  1626. return false;
  1627. if (CEREAL_RAPIDJSON_UNLIKELY(!m->value.Accept(handler)))
  1628. return false;
  1629. }
  1630. return handler.EndObject(data_.o.size);
  1631. case kArrayType:
  1632. if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartArray()))
  1633. return false;
  1634. for (const GenericValue* v = Begin(); v != End(); ++v)
  1635. if (CEREAL_RAPIDJSON_UNLIKELY(!v->Accept(handler)))
  1636. return false;
  1637. return handler.EndArray(data_.a.size);
  1638. case kStringType:
  1639. return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0);
  1640. default:
  1641. CEREAL_RAPIDJSON_ASSERT(GetType() == kNumberType);
  1642. if (IsDouble()) return handler.Double(data_.n.d);
  1643. else if (IsInt()) return handler.Int(data_.n.i.i);
  1644. else if (IsUint()) return handler.Uint(data_.n.u.u);
  1645. else if (IsInt64()) return handler.Int64(data_.n.i64);
  1646. else return handler.Uint64(data_.n.u64);
  1647. }
  1648. }
  1649. private:
  1650. template <typename, typename> friend class GenericValue;
  1651. template <typename, typename, typename> friend class GenericDocument;
  1652. enum {
  1653. kBoolFlag = 0x0008,
  1654. kNumberFlag = 0x0010,
  1655. kIntFlag = 0x0020,
  1656. kUintFlag = 0x0040,
  1657. kInt64Flag = 0x0080,
  1658. kUint64Flag = 0x0100,
  1659. kDoubleFlag = 0x0200,
  1660. kStringFlag = 0x0400,
  1661. kCopyFlag = 0x0800,
  1662. kInlineStrFlag = 0x1000,
  1663. // Initial flags of different types.
  1664. kNullFlag = kNullType,
  1665. kTrueFlag = kTrueType | kBoolFlag,
  1666. kFalseFlag = kFalseType | kBoolFlag,
  1667. kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
  1668. kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
  1669. kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
  1670. kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
  1671. kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
  1672. kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag,
  1673. kConstStringFlag = kStringType | kStringFlag,
  1674. kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
  1675. kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag,
  1676. kObjectFlag = kObjectType,
  1677. kArrayFlag = kArrayType,
  1678. kTypeMask = 0x07
  1679. };
  1680. static const SizeType kDefaultArrayCapacity = 16;
  1681. static const SizeType kDefaultObjectCapacity = 16;
  1682. struct Flag {
  1683. #if CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION
  1684. char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer
  1685. #elif CEREAL_RAPIDJSON_64BIT
  1686. char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes
  1687. #else
  1688. char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes
  1689. #endif
  1690. uint16_t flags;
  1691. };
  1692. struct String {
  1693. SizeType length;
  1694. SizeType hashcode; //!< reserved
  1695. const Ch* str;
  1696. }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
  1697. // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars
  1698. // (excluding the terminating zero) and store a value to determine the length of the contained
  1699. // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string
  1700. // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as
  1701. // the string terminator as well. For getting the string length back from that value just use
  1702. // "MaxSize - str[LenPos]".
  1703. // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode,
  1704. // 13-chars strings for CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings).
  1705. struct ShortString {
  1706. enum { MaxChars = sizeof(static_cast<Flag*>(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize };
  1707. Ch str[MaxChars];
  1708. inline static bool Usable(SizeType len) { return (MaxSize >= len); }
  1709. inline void SetLength(SizeType len) { str[LenPos] = static_cast<Ch>(MaxSize - len); }
  1710. inline SizeType GetLength() const { return static_cast<SizeType>(MaxSize - str[LenPos]); }
  1711. }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
  1712. // By using proper binary layout, retrieval of different integer types do not need conversions.
  1713. union Number {
  1714. #if CEREAL_RAPIDJSON_ENDIAN == CEREAL_RAPIDJSON_LITTLEENDIAN
  1715. struct I {
  1716. int i;
  1717. char padding[4];
  1718. }i;
  1719. struct U {
  1720. unsigned u;
  1721. char padding2[4];
  1722. }u;
  1723. #else
  1724. struct I {
  1725. char padding[4];
  1726. int i;
  1727. }i;
  1728. struct U {
  1729. char padding2[4];
  1730. unsigned u;
  1731. }u;
  1732. #endif
  1733. int64_t i64;
  1734. uint64_t u64;
  1735. double d;
  1736. }; // 8 bytes
  1737. struct ObjectData {
  1738. SizeType size;
  1739. SizeType capacity;
  1740. Member* members;
  1741. }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
  1742. struct ArrayData {
  1743. SizeType size;
  1744. SizeType capacity;
  1745. GenericValue* elements;
  1746. }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
  1747. union Data {
  1748. String s;
  1749. ShortString ss;
  1750. Number n;
  1751. ObjectData o;
  1752. ArrayData a;
  1753. Flag f;
  1754. }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION
  1755. CEREAL_RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(Ch, data_.s.str); }
  1756. CEREAL_RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return CEREAL_RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); }
  1757. CEREAL_RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); }
  1758. CEREAL_RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return CEREAL_RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); }
  1759. CEREAL_RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(Member, data_.o.members); }
  1760. CEREAL_RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return CEREAL_RAPIDJSON_SETPOINTER(Member, data_.o.members, members); }
  1761. // Initialize this value as array with initial data, without calling destructor.
  1762. void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) {
  1763. data_.f.flags = kArrayFlag;
  1764. if (count) {
  1765. GenericValue* e = static_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue)));
  1766. SetElementsPointer(e);
  1767. std::memcpy(static_cast<void*>(e), values, count * sizeof(GenericValue));
  1768. }
  1769. else
  1770. SetElementsPointer(0);
  1771. data_.a.size = data_.a.capacity = count;
  1772. }
  1773. //! Initialize this value as object with initial data, without calling destructor.
  1774. void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
  1775. data_.f.flags = kObjectFlag;
  1776. if (count) {
  1777. Member* m = static_cast<Member*>(allocator.Malloc(count * sizeof(Member)));
  1778. SetMembersPointer(m);
  1779. std::memcpy(static_cast<void*>(m), members, count * sizeof(Member));
  1780. }
  1781. else
  1782. SetMembersPointer(0);
  1783. data_.o.size = data_.o.capacity = count;
  1784. }
  1785. //! Initialize this value as constant string, without calling destructor.
  1786. void SetStringRaw(StringRefType s) CEREAL_RAPIDJSON_NOEXCEPT {
  1787. data_.f.flags = kConstStringFlag;
  1788. SetStringPointer(s);
  1789. data_.s.length = s.length;
  1790. }
  1791. //! Initialize this value as copy string with initial data, without calling destructor.
  1792. void SetStringRaw(StringRefType s, Allocator& allocator) {
  1793. Ch* str = 0;
  1794. if (ShortString::Usable(s.length)) {
  1795. data_.f.flags = kShortStringFlag;
  1796. data_.ss.SetLength(s.length);
  1797. str = data_.ss.str;
  1798. } else {
  1799. data_.f.flags = kCopyStringFlag;
  1800. data_.s.length = s.length;
  1801. str = static_cast<Ch *>(allocator.Malloc((s.length + 1) * sizeof(Ch)));
  1802. SetStringPointer(str);
  1803. }
  1804. std::memcpy(str, s, s.length * sizeof(Ch));
  1805. str[s.length] = '\0';
  1806. }
  1807. //! Assignment without calling destructor
  1808. void RawAssign(GenericValue& rhs) CEREAL_RAPIDJSON_NOEXCEPT {
  1809. data_ = rhs.data_;
  1810. // data_.f.flags = rhs.data_.f.flags;
  1811. rhs.data_.f.flags = kNullFlag;
  1812. }
  1813. template <typename SourceAllocator>
  1814. bool StringEqual(const GenericValue<Encoding, SourceAllocator>& rhs) const {
  1815. CEREAL_RAPIDJSON_ASSERT(IsString());
  1816. CEREAL_RAPIDJSON_ASSERT(rhs.IsString());
  1817. const SizeType len1 = GetStringLength();
  1818. const SizeType len2 = rhs.GetStringLength();
  1819. if(len1 != len2) { return false; }
  1820. const Ch* const str1 = GetString();
  1821. const Ch* const str2 = rhs.GetString();
  1822. if(str1 == str2) { return true; } // fast path for constant string
  1823. return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0);
  1824. }
  1825. Data data_;
  1826. };
  1827. //! GenericValue with UTF8 encoding
  1828. typedef GenericValue<UTF8<> > Value;
  1829. ///////////////////////////////////////////////////////////////////////////////
  1830. // GenericDocument
  1831. //! A document for parsing JSON text as DOM.
  1832. /*!
  1833. \note implements Handler concept
  1834. \tparam Encoding Encoding for both parsing and string storage.
  1835. \tparam Allocator Allocator for allocating memory for the DOM
  1836. \tparam StackAllocator Allocator for allocating memory for stack during parsing.
  1837. \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue.
  1838. */
  1839. template <typename Encoding, typename Allocator = MemoryPoolAllocator<>, typename StackAllocator = CrtAllocator>
  1840. class GenericDocument : public GenericValue<Encoding, Allocator> {
  1841. public:
  1842. typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
  1843. typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.
  1844. typedef Allocator AllocatorType; //!< Allocator type from template parameter.
  1845. //! Constructor
  1846. /*! Creates an empty document of specified type.
  1847. \param type Mandatory type of object to create.
  1848. \param allocator Optional allocator for allocating memory.
  1849. \param stackCapacity Optional initial capacity of stack in bytes.
  1850. \param stackAllocator Optional allocator for allocating memory for stack.
  1851. */
  1852. explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
  1853. GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
  1854. {
  1855. if (!allocator_)
  1856. ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)();
  1857. }
  1858. //! Constructor
  1859. /*! Creates an empty document which type is Null.
  1860. \param allocator Optional allocator for allocating memory.
  1861. \param stackCapacity Optional initial capacity of stack in bytes.
  1862. \param stackAllocator Optional allocator for allocating memory for stack.
  1863. */
  1864. GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
  1865. allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
  1866. {
  1867. if (!allocator_)
  1868. ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)();
  1869. }
  1870. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1871. //! Move constructor in C++11
  1872. GenericDocument(GenericDocument&& rhs) CEREAL_RAPIDJSON_NOEXCEPT
  1873. : ValueType(std::forward<ValueType>(rhs)), // explicit cast to avoid prohibited move from Document
  1874. allocator_(rhs.allocator_),
  1875. ownAllocator_(rhs.ownAllocator_),
  1876. stack_(std::move(rhs.stack_)),
  1877. parseResult_(rhs.parseResult_)
  1878. {
  1879. rhs.allocator_ = 0;
  1880. rhs.ownAllocator_ = 0;
  1881. rhs.parseResult_ = ParseResult();
  1882. }
  1883. #endif
  1884. ~GenericDocument() {
  1885. Destroy();
  1886. }
  1887. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  1888. //! Move assignment in C++11
  1889. GenericDocument& operator=(GenericDocument&& rhs) CEREAL_RAPIDJSON_NOEXCEPT
  1890. {
  1891. // The cast to ValueType is necessary here, because otherwise it would
  1892. // attempt to call GenericValue's templated assignment operator.
  1893. ValueType::operator=(std::forward<ValueType>(rhs));
  1894. // Calling the destructor here would prematurely call stack_'s destructor
  1895. Destroy();
  1896. allocator_ = rhs.allocator_;
  1897. ownAllocator_ = rhs.ownAllocator_;
  1898. stack_ = std::move(rhs.stack_);
  1899. parseResult_ = rhs.parseResult_;
  1900. rhs.allocator_ = 0;
  1901. rhs.ownAllocator_ = 0;
  1902. rhs.parseResult_ = ParseResult();
  1903. return *this;
  1904. }
  1905. #endif
  1906. //! Exchange the contents of this document with those of another.
  1907. /*!
  1908. \param rhs Another document.
  1909. \note Constant complexity.
  1910. \see GenericValue::Swap
  1911. */
  1912. GenericDocument& Swap(GenericDocument& rhs) CEREAL_RAPIDJSON_NOEXCEPT {
  1913. ValueType::Swap(rhs);
  1914. stack_.Swap(rhs.stack_);
  1915. internal::Swap(allocator_, rhs.allocator_);
  1916. internal::Swap(ownAllocator_, rhs.ownAllocator_);
  1917. internal::Swap(parseResult_, rhs.parseResult_);
  1918. return *this;
  1919. }
  1920. // Allow Swap with ValueType.
  1921. // Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names.
  1922. using ValueType::Swap;
  1923. //! free-standing swap function helper
  1924. /*!
  1925. Helper function to enable support for common swap implementation pattern based on \c std::swap:
  1926. \code
  1927. void swap(MyClass& a, MyClass& b) {
  1928. using std::swap;
  1929. swap(a.doc, b.doc);
  1930. // ...
  1931. }
  1932. \endcode
  1933. \see Swap()
  1934. */
  1935. friend inline void swap(GenericDocument& a, GenericDocument& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); }
  1936. //! Populate this document by a generator which produces SAX events.
  1937. /*! \tparam Generator A functor with <tt>bool f(Handler)</tt> prototype.
  1938. \param g Generator functor which sends SAX events to the parameter.
  1939. \return The document itself for fluent API.
  1940. */
  1941. template <typename Generator>
  1942. GenericDocument& Populate(Generator& g) {
  1943. ClearStackOnExit scope(*this);
  1944. if (g(*this)) {
  1945. CEREAL_RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
  1946. ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document
  1947. }
  1948. return *this;
  1949. }
  1950. //!@name Parse from stream
  1951. //!@{
  1952. //! Parse JSON text from an input stream (with Encoding conversion)
  1953. /*! \tparam parseFlags Combination of \ref ParseFlag.
  1954. \tparam SourceEncoding Encoding of input stream
  1955. \tparam InputStream Type of input stream, implementing Stream concept
  1956. \param is Input stream to be parsed.
  1957. \return The document itself for fluent API.
  1958. */
  1959. template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
  1960. GenericDocument& ParseStream(InputStream& is) {
  1961. GenericReader<SourceEncoding, Encoding, StackAllocator> reader(
  1962. stack_.HasAllocator() ? &stack_.GetAllocator() : 0);
  1963. ClearStackOnExit scope(*this);
  1964. parseResult_ = reader.template Parse<parseFlags>(is, *this);
  1965. if (parseResult_) {
  1966. CEREAL_RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
  1967. ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document
  1968. }
  1969. return *this;
  1970. }
  1971. //! Parse JSON text from an input stream
  1972. /*! \tparam parseFlags Combination of \ref ParseFlag.
  1973. \tparam InputStream Type of input stream, implementing Stream concept
  1974. \param is Input stream to be parsed.
  1975. \return The document itself for fluent API.
  1976. */
  1977. template <unsigned parseFlags, typename InputStream>
  1978. GenericDocument& ParseStream(InputStream& is) {
  1979. return ParseStream<parseFlags, Encoding, InputStream>(is);
  1980. }
  1981. //! Parse JSON text from an input stream (with \ref kParseDefaultFlags)
  1982. /*! \tparam InputStream Type of input stream, implementing Stream concept
  1983. \param is Input stream to be parsed.
  1984. \return The document itself for fluent API.
  1985. */
  1986. template <typename InputStream>
  1987. GenericDocument& ParseStream(InputStream& is) {
  1988. return ParseStream<kParseDefaultFlags, Encoding, InputStream>(is);
  1989. }
  1990. //!@}
  1991. //!@name Parse in-place from mutable string
  1992. //!@{
  1993. //! Parse JSON text from a mutable string
  1994. /*! \tparam parseFlags Combination of \ref ParseFlag.
  1995. \param str Mutable zero-terminated string to be parsed.
  1996. \return The document itself for fluent API.
  1997. */
  1998. template <unsigned parseFlags>
  1999. GenericDocument& ParseInsitu(Ch* str) {
  2000. GenericInsituStringStream<Encoding> s(str);
  2001. return ParseStream<parseFlags | kParseInsituFlag>(s);
  2002. }
  2003. //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags)
  2004. /*! \param str Mutable zero-terminated string to be parsed.
  2005. \return The document itself for fluent API.
  2006. */
  2007. GenericDocument& ParseInsitu(Ch* str) {
  2008. return ParseInsitu<kParseDefaultFlags>(str);
  2009. }
  2010. //!@}
  2011. //!@name Parse from read-only string
  2012. //!@{
  2013. //! Parse JSON text from a read-only string (with Encoding conversion)
  2014. /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
  2015. \tparam SourceEncoding Transcoding from input Encoding
  2016. \param str Read-only zero-terminated string to be parsed.
  2017. */
  2018. template <unsigned parseFlags, typename SourceEncoding>
  2019. GenericDocument& Parse(const typename SourceEncoding::Ch* str) {
  2020. CEREAL_RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
  2021. GenericStringStream<SourceEncoding> s(str);
  2022. return ParseStream<parseFlags, SourceEncoding>(s);
  2023. }
  2024. //! Parse JSON text from a read-only string
  2025. /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
  2026. \param str Read-only zero-terminated string to be parsed.
  2027. */
  2028. template <unsigned parseFlags>
  2029. GenericDocument& Parse(const Ch* str) {
  2030. return Parse<parseFlags, Encoding>(str);
  2031. }
  2032. //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags)
  2033. /*! \param str Read-only zero-terminated string to be parsed.
  2034. */
  2035. GenericDocument& Parse(const Ch* str) {
  2036. return Parse<kParseDefaultFlags>(str);
  2037. }
  2038. template <unsigned parseFlags, typename SourceEncoding>
  2039. GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) {
  2040. CEREAL_RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
  2041. MemoryStream ms(reinterpret_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch));
  2042. EncodedInputStream<SourceEncoding, MemoryStream> is(ms);
  2043. ParseStream<parseFlags, SourceEncoding>(is);
  2044. return *this;
  2045. }
  2046. template <unsigned parseFlags>
  2047. GenericDocument& Parse(const Ch* str, size_t length) {
  2048. return Parse<parseFlags, Encoding>(str, length);
  2049. }
  2050. GenericDocument& Parse(const Ch* str, size_t length) {
  2051. return Parse<kParseDefaultFlags>(str, length);
  2052. }
  2053. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2054. template <unsigned parseFlags, typename SourceEncoding>
  2055. GenericDocument& Parse(const std::basic_string<typename SourceEncoding::Ch>& str) {
  2056. // c_str() is constant complexity according to standard. Should be faster than Parse(const char*, size_t)
  2057. return Parse<parseFlags, SourceEncoding>(str.c_str());
  2058. }
  2059. template <unsigned parseFlags>
  2060. GenericDocument& Parse(const std::basic_string<Ch>& str) {
  2061. return Parse<parseFlags, Encoding>(str.c_str());
  2062. }
  2063. GenericDocument& Parse(const std::basic_string<Ch>& str) {
  2064. return Parse<kParseDefaultFlags>(str);
  2065. }
  2066. #endif // CEREAL_RAPIDJSON_HAS_STDSTRING
  2067. //!@}
  2068. //!@name Handling parse errors
  2069. //!@{
  2070. //! Whether a parse error has occurred in the last parsing.
  2071. bool HasParseError() const { return parseResult_.IsError(); }
  2072. //! Get the \ref ParseErrorCode of last parsing.
  2073. ParseErrorCode GetParseError() const { return parseResult_.Code(); }
  2074. //! Get the position of last parsing error in input, 0 otherwise.
  2075. size_t GetErrorOffset() const { return parseResult_.Offset(); }
  2076. //! Implicit conversion to get the last parse result
  2077. #ifndef __clang // -Wdocumentation
  2078. /*! \return \ref ParseResult of the last parse operation
  2079. \code
  2080. Document doc;
  2081. ParseResult ok = doc.Parse(json);
  2082. if (!ok)
  2083. printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset());
  2084. \endcode
  2085. */
  2086. #endif
  2087. operator ParseResult() const { return parseResult_; }
  2088. //!@}
  2089. //! Get the allocator of this document.
  2090. Allocator& GetAllocator() {
  2091. CEREAL_RAPIDJSON_ASSERT(allocator_);
  2092. return *allocator_;
  2093. }
  2094. //! Get the capacity of stack in bytes.
  2095. size_t GetStackCapacity() const { return stack_.GetCapacity(); }
  2096. private:
  2097. // clear stack on any exit from ParseStream, e.g. due to exception
  2098. struct ClearStackOnExit {
  2099. explicit ClearStackOnExit(GenericDocument& d) : d_(d) {}
  2100. ~ClearStackOnExit() { d_.ClearStack(); }
  2101. private:
  2102. ClearStackOnExit(const ClearStackOnExit&);
  2103. ClearStackOnExit& operator=(const ClearStackOnExit&);
  2104. GenericDocument& d_;
  2105. };
  2106. // callers of the following private Handler functions
  2107. // template <typename,typename,typename> friend class GenericReader; // for parsing
  2108. template <typename, typename> friend class GenericValue; // for deep copying
  2109. public:
  2110. // Implementation of Handler
  2111. bool Null() { new (stack_.template Push<ValueType>()) ValueType(); return true; }
  2112. bool Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); return true; }
  2113. bool Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
  2114. bool Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
  2115. bool Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
  2116. bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
  2117. bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; }
  2118. bool RawNumber(const Ch* str, SizeType length, bool copy) {
  2119. if (copy)
  2120. new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
  2121. else
  2122. new (stack_.template Push<ValueType>()) ValueType(str, length);
  2123. return true;
  2124. }
  2125. bool String(const Ch* str, SizeType length, bool copy) {
  2126. if (copy)
  2127. new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
  2128. else
  2129. new (stack_.template Push<ValueType>()) ValueType(str, length);
  2130. return true;
  2131. }
  2132. bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; }
  2133. bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); }
  2134. bool EndObject(SizeType memberCount) {
  2135. typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount);
  2136. stack_.template Top<ValueType>()->SetObjectRaw(members, memberCount, GetAllocator());
  2137. return true;
  2138. }
  2139. bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; }
  2140. bool EndArray(SizeType elementCount) {
  2141. ValueType* elements = stack_.template Pop<ValueType>(elementCount);
  2142. stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator());
  2143. return true;
  2144. }
  2145. private:
  2146. //! Prohibit copying
  2147. GenericDocument(const GenericDocument&);
  2148. //! Prohibit assignment
  2149. GenericDocument& operator=(const GenericDocument&);
  2150. void ClearStack() {
  2151. if (Allocator::kNeedFree)
  2152. while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects)
  2153. (stack_.template Pop<ValueType>(1))->~ValueType();
  2154. else
  2155. stack_.Clear();
  2156. stack_.ShrinkToFit();
  2157. }
  2158. void Destroy() {
  2159. CEREAL_RAPIDJSON_DELETE(ownAllocator_);
  2160. }
  2161. static const size_t kDefaultStackCapacity = 1024;
  2162. Allocator* allocator_;
  2163. Allocator* ownAllocator_;
  2164. internal::Stack<StackAllocator> stack_;
  2165. ParseResult parseResult_;
  2166. };
  2167. //! GenericDocument with UTF8 encoding
  2168. typedef GenericDocument<UTF8<> > Document;
  2169. //! Helper class for accessing Value of array type.
  2170. /*!
  2171. Instance of this helper class is obtained by \c GenericValue::GetArray().
  2172. In addition to all APIs for array type, it provides range-based for loop if \c CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR=1.
  2173. */
  2174. template <bool Const, typename ValueT>
  2175. class GenericArray {
  2176. public:
  2177. typedef GenericArray<true, ValueT> ConstArray;
  2178. typedef GenericArray<false, ValueT> Array;
  2179. typedef ValueT PlainType;
  2180. typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
  2181. typedef ValueType* ValueIterator; // This may be const or non-const iterator
  2182. typedef const ValueT* ConstValueIterator;
  2183. typedef typename ValueType::AllocatorType AllocatorType;
  2184. typedef typename ValueType::StringRefType StringRefType;
  2185. template <typename, typename>
  2186. friend class GenericValue;
  2187. GenericArray(const GenericArray& rhs) : value_(rhs.value_) {}
  2188. GenericArray& operator=(const GenericArray& rhs) { value_ = rhs.value_; return *this; }
  2189. ~GenericArray() {}
  2190. SizeType Size() const { return value_.Size(); }
  2191. SizeType Capacity() const { return value_.Capacity(); }
  2192. bool Empty() const { return value_.Empty(); }
  2193. void Clear() const { value_.Clear(); }
  2194. ValueType& operator[](SizeType index) const { return value_[index]; }
  2195. ValueIterator Begin() const { return value_.Begin(); }
  2196. ValueIterator End() const { return value_.End(); }
  2197. GenericArray Reserve(SizeType newCapacity, AllocatorType &allocator) const { value_.Reserve(newCapacity, allocator); return *this; }
  2198. GenericArray PushBack(ValueType& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
  2199. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  2200. GenericArray PushBack(ValueType&& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
  2201. #endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  2202. GenericArray PushBack(StringRefType value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
  2203. template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (const GenericArray&)) PushBack(T value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
  2204. GenericArray PopBack() const { value_.PopBack(); return *this; }
  2205. ValueIterator Erase(ConstValueIterator pos) const { return value_.Erase(pos); }
  2206. ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) const { return value_.Erase(first, last); }
  2207. #if CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR
  2208. ValueIterator begin() const { return value_.Begin(); }
  2209. ValueIterator end() const { return value_.End(); }
  2210. #endif
  2211. private:
  2212. GenericArray();
  2213. GenericArray(ValueType& value) : value_(value) {}
  2214. ValueType& value_;
  2215. };
  2216. //! Helper class for accessing Value of object type.
  2217. /*!
  2218. Instance of this helper class is obtained by \c GenericValue::GetObject().
  2219. In addition to all APIs for array type, it provides range-based for loop if \c CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR=1.
  2220. */
  2221. template <bool Const, typename ValueT>
  2222. class GenericObject {
  2223. public:
  2224. typedef GenericObject<true, ValueT> ConstObject;
  2225. typedef GenericObject<false, ValueT> Object;
  2226. typedef ValueT PlainType;
  2227. typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
  2228. typedef GenericMemberIterator<Const, typename ValueT::EncodingType, typename ValueT::AllocatorType> MemberIterator; // This may be const or non-const iterator
  2229. typedef GenericMemberIterator<true, typename ValueT::EncodingType, typename ValueT::AllocatorType> ConstMemberIterator;
  2230. typedef typename ValueType::AllocatorType AllocatorType;
  2231. typedef typename ValueType::StringRefType StringRefType;
  2232. typedef typename ValueType::EncodingType EncodingType;
  2233. typedef typename ValueType::Ch Ch;
  2234. template <typename, typename>
  2235. friend class GenericValue;
  2236. GenericObject(const GenericObject& rhs) : value_(rhs.value_) {}
  2237. GenericObject& operator=(const GenericObject& rhs) { value_ = rhs.value_; return *this; }
  2238. ~GenericObject() {}
  2239. SizeType MemberCount() const { return value_.MemberCount(); }
  2240. SizeType MemberCapacity() const { return value_.MemberCapacity(); }
  2241. bool ObjectEmpty() const { return value_.ObjectEmpty(); }
  2242. template <typename T> ValueType& operator[](T* name) const { return value_[name]; }
  2243. template <typename SourceAllocator> ValueType& operator[](const GenericValue<EncodingType, SourceAllocator>& name) const { return value_[name]; }
  2244. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2245. ValueType& operator[](const std::basic_string<Ch>& name) const { return value_[name]; }
  2246. #endif
  2247. MemberIterator MemberBegin() const { return value_.MemberBegin(); }
  2248. MemberIterator MemberEnd() const { return value_.MemberEnd(); }
  2249. GenericObject MemberReserve(SizeType newCapacity, AllocatorType &allocator) const { value_.MemberReserve(newCapacity, allocator); return *this; }
  2250. bool HasMember(const Ch* name) const { return value_.HasMember(name); }
  2251. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2252. bool HasMember(const std::basic_string<Ch>& name) const { return value_.HasMember(name); }
  2253. #endif
  2254. template <typename SourceAllocator> bool HasMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.HasMember(name); }
  2255. MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); }
  2256. template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.FindMember(name); }
  2257. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2258. MemberIterator FindMember(const std::basic_string<Ch>& name) const { return value_.FindMember(name); }
  2259. #endif
  2260. GenericObject AddMember(ValueType& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2261. GenericObject AddMember(ValueType& name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2262. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2263. GenericObject AddMember(ValueType& name, std::basic_string<Ch>& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2264. #endif
  2265. template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) AddMember(ValueType& name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2266. #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  2267. GenericObject AddMember(ValueType&& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2268. GenericObject AddMember(ValueType&& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2269. GenericObject AddMember(ValueType& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2270. GenericObject AddMember(StringRefType name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2271. #endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS
  2272. GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2273. GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2274. template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
  2275. void RemoveAllMembers() { value_.RemoveAllMembers(); }
  2276. bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); }
  2277. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2278. bool RemoveMember(const std::basic_string<Ch>& name) const { return value_.RemoveMember(name); }
  2279. #endif
  2280. template <typename SourceAllocator> bool RemoveMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.RemoveMember(name); }
  2281. MemberIterator RemoveMember(MemberIterator m) const { return value_.RemoveMember(m); }
  2282. MemberIterator EraseMember(ConstMemberIterator pos) const { return value_.EraseMember(pos); }
  2283. MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) const { return value_.EraseMember(first, last); }
  2284. bool EraseMember(const Ch* name) const { return value_.EraseMember(name); }
  2285. #if CEREAL_RAPIDJSON_HAS_STDSTRING
  2286. bool EraseMember(const std::basic_string<Ch>& name) const { return EraseMember(ValueType(StringRef(name))); }
  2287. #endif
  2288. template <typename SourceAllocator> bool EraseMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.EraseMember(name); }
  2289. #if CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR
  2290. MemberIterator begin() const { return value_.MemberBegin(); }
  2291. MemberIterator end() const { return value_.MemberEnd(); }
  2292. #endif
  2293. private:
  2294. GenericObject();
  2295. GenericObject(ValueType& value) : value_(value) {}
  2296. ValueType& value_;
  2297. };
  2298. CEREAL_RAPIDJSON_NAMESPACE_END
  2299. CEREAL_RAPIDJSON_DIAG_POP
  2300. #endif // CEREAL_RAPIDJSON_DOCUMENT_H_