document.h 115 KB

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