document.h 111 KB

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