document.h 115 KB

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