document.h 115 KB

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