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