document.h 84 KB

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