document.h 116 KB

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