document.h 131 KB

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