2
0

document.h 90 KB

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