All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
document.h
1 #ifndef RAPIDJSON_DOCUMENT_H_
2 #define RAPIDJSON_DOCUMENT_H_
3 
4 #include "reader.h"
5 #include "internal/strfunc.h"
6 #include <new> // placement new
7 
8 #ifdef _MSC_VER
9 RAPIDJSON_DIAG_PUSH
10 RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
11 #elif defined(__GNUC__)
12 RAPIDJSON_DIAG_PUSH
13 RAPIDJSON_DIAG_OFF(effc++)
14 #endif
15 
16 #ifndef RAPIDJSON_NOMEMBERITERATORCLASS
17 #include "internal/meta.h"
18 #include <iterator> // std::iterator, std::random_access_iterator_tag
19 #endif
20 
21 namespace rapidjson {
22 
23 // Forward declaration.
24 template <typename Encoding, typename Allocator>
26 
27 //! Name-value pair in a JSON object value.
28 /*!
29  This class was internal to GenericValue. It used to be a inner struct.
30  But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct.
31  https://code.google.com/p/rapidjson/issues/detail?id=64
32 */
33 template <typename Encoding, typename Allocator>
34 struct GenericMember {
35  GenericValue<Encoding, Allocator> name; //!< name of member (must be a string)
37 };
38 
39 #ifndef RAPIDJSON_NOMEMBERITERATORCLASS
40 
41 //! (Constant) member iterator for a JSON object value
42 /*!
43  \tparam Const Is this a constant iterator?
44  \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
45  \tparam Allocator Allocator type for allocating memory of object, array and string.
46 
47  This class implements a Random Access Iterator for GenericMember elements
48  of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements].
49 
50  \note This iterator implementation is mainly intended to avoid implicit
51  conversions from iterator values to \c NULL,
52  e.g. from GenericValue::FindMember.
53 
54  \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a
55  pointer-based implementation, if your platform doesn't provide
56  the C++ <iterator> header.
57 
58  \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
59  */
60 template <bool Const, typename Encoding, typename Allocator>
62  : public std::iterator<std::random_access_iterator_tag
63  , typename internal::MaybeAddConst<Const,GenericMember<Encoding,Allocator> >::Type> {
64 
65  friend class GenericValue<Encoding,Allocator>;
66  template <bool, typename, typename> friend class GenericMemberIterator;
67 
69  typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
70  typedef std::iterator<std::random_access_iterator_tag,ValueType> BaseType;
71 
72 public:
73  //! Iterator type itself
75  //! Constant iterator type
77  //! Non-constant iterator type
79 
80  //! Pointer to (const) GenericMember
81  typedef typename BaseType::pointer Pointer;
82  //! Reference to (const) GenericMember
83  typedef typename BaseType::reference Reference;
84  //! Signed integer type (e.g. \c ptrdiff_t)
85  typedef typename BaseType::difference_type DifferenceType;
86 
87  //! Default constructor (singular value)
88  /*! Creates an iterator pointing to no element.
89  \note All operations, except for comparisons, are undefined on such values.
90  */
91  GenericMemberIterator() : ptr_() {}
92 
93  //! Iterator conversions to more const
94  /*!
95  \param it (Non-const) iterator to copy from
96 
97  Allows the creation of an iterator from another GenericMemberIterator
98  that is "less const". Especially, creating a non-constant iterator
99  from a constant iterator are disabled:
100  \li const -> non-const (not ok)
101  \li const -> const (ok)
102  \li non-const -> const (ok)
103  \li non-const -> non-const (ok)
104 
105  \note If the \c Const template parameter is already \c false, this
106  constructor effectively defines a regular copy-constructor.
107  Otherwise, the copy constructor is implicitly defined.
108  */
109  GenericMemberIterator(const NonConstType & it) : ptr_( it.ptr_ ) {}
110 
111  //! @name stepping
112  //@{
113  Iterator& operator++(){ ++ptr_; return *this; }
114  Iterator& operator--(){ --ptr_; return *this; }
115  Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; }
116  Iterator operator--(int){ Iterator old(*this); --ptr_; return old; }
117  //@}
118 
119  //! @name increment/decrement
120  //@{
121  Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); }
122  Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); }
123 
124  Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; }
125  Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; }
126  //@}
127 
128  //! @name relations
129  //@{
130  bool operator==(Iterator that) const { return ptr_ == that.ptr_; }
131  bool operator!=(Iterator that) const { return ptr_ != that.ptr_; }
132  bool operator<=(Iterator that) const { return ptr_ <= that.ptr_; }
133  bool operator>=(Iterator that) const { return ptr_ >= that.ptr_; }
134  bool operator< (Iterator that) const { return ptr_ < that.ptr_; }
135  bool operator> (Iterator that) const { return ptr_ > that.ptr_; }
136  //@}
137 
138  //! @name dereference
139  //@{
140  Reference operator*() const { return *ptr_; }
141  Pointer operator->() const { return ptr_; }
142  Reference operator[](DifferenceType n) const { return ptr_[n]; }
143  //@}
144 
145  //! Distance
146  DifferenceType operator-(Iterator that) const { return ptr_-that.ptr_; }
147 
148 private:
149  //! Internal constructor from plain pointer
150  explicit GenericMemberIterator(Pointer p) : ptr_(p) {}
151 
152  Pointer ptr_; //!< raw pointer
153 };
154 
155 #else // RAPIDJSON_NOMEMBERITERATORCLASS
156 
157 // class-based member iterator implementation disabled, use plain pointers
158 
159 template <bool Const, typename Encoding, typename Allocator>
160 struct GenericMemberIterator;
161 
162 //! non-const GenericMemberIterator
163 template <typename Encoding, typename Allocator>
164 struct GenericMemberIterator<false,Encoding,Allocator> {
165  //! use plain pointer as iterator type
166  typedef GenericMember<Encoding,Allocator>* Iterator;
167 };
168 //! const GenericMemberIterator
169 template <typename Encoding, typename Allocator>
170 struct GenericMemberIterator<true,Encoding,Allocator> {
171  //! use plain const pointer as iterator type
172  typedef const GenericMember<Encoding,Allocator>* Iterator;
173 };
174 
175 #endif // RAPIDJSON_NOMEMBERITERATORCLASS
176 
177 ///////////////////////////////////////////////////////////////////////////////
178 // GenericStringRef
179 
180 //! Reference to a constant string (not taking a copy)
181 /*!
182  \tparam CharType character type of the string
183 
184  This helper class is used to automatically infer constant string
185  references for string literals, especially from \c const \b (!)
186  character arrays.
187 
188  The main use is for creating JSON string values without copying the
189  source string via an \ref Allocator. This requires that the referenced
190  string pointers have a sufficient lifetime, which exceeds the lifetime
191  of the associated GenericValue.
192 
193  \b Example
194  \code
195  Value v("foo"); // ok, no need to copy & calculate length
196  const char foo[] = "foo";
197  v.SetString(foo); // ok
198 
199  const char* bar = foo;
200  // Value x(bar); // not ok, can't rely on bar's lifetime
201  Value x(StringRef(bar)); // lifetime explicitly guaranteed by user
202  Value y(StringRef(bar, 3)); // ok, explicitly pass length
203  \endcode
204 
205  \see StringRef, GenericValue::SetString
206 */
207 template<typename CharType>
209  typedef CharType Ch; //!< character type of the string
210 
211  //! Create string reference from \c const character array
212  /*!
213  This constructor implicitly creates a constant string reference from
214  a \c const character array. It has better performance than
215  \ref StringRef(const CharType*) by inferring the string \ref length
216  from the array length, and also supports strings containing null
217  characters.
218 
219  \tparam N length of the string, automatically inferred
220 
221  \param str Constant character array, lifetime assumed to be longer
222  than the use of the string in e.g. a GenericValue
223 
224  \post \ref s == str
225 
226  \note Constant complexity.
227  \note There is a hidden, private overload to disallow references to
228  non-const character arrays to be created via this constructor.
229  By this, e.g. function-scope arrays used to be filled via
230  \c snprintf are excluded from consideration.
231  In such cases, the referenced string should be \b copied to the
232  GenericValue instead.
233  */
234  template<SizeType N>
235  GenericStringRef(const CharType (&str)[N])
236  : s(str), length(N-1) {}
237 
238  //! Explicitly create string reference from \c const character pointer
239  /*!
240  This constructor can be used to \b explicitly create a reference to
241  a constant string pointer.
242 
243  \see StringRef(const CharType*)
244 
245  \param str Constant character pointer, lifetime assumed to be longer
246  than the use of the string in e.g. a GenericValue
247 
248  \post \ref s == str
249 
250  \note There is a hidden, private overload to disallow references to
251  non-const character arrays to be created via this constructor.
252  By this, e.g. function-scope arrays used to be filled via
253  \c snprintf are excluded from consideration.
254  In such cases, the referenced string should be \b copied to the
255  GenericValue instead.
256  */
257  explicit GenericStringRef(const CharType* str)
258  : s(str), length(internal::StrLen(str)){}
259 
260  //! Create constant string reference from pointer and length
261  /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
262  \param len length of the string, excluding the trailing NULL terminator
263 
264  \post \ref s == str && \ref length == len
265  \note Constant complexity.
266  */
267  GenericStringRef(const CharType* str, SizeType len)
268  : s(str), length(len) { RAPIDJSON_ASSERT(s != NULL); }
269 
270  //! implicit conversion to plain CharType pointer
271  operator const Ch *() const { return s; }
272 
273  const Ch* const s; //!< plain CharType pointer
274  const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
275 
276 private:
277  //! Disallow copy-assignment
278  GenericStringRef operator=(const GenericStringRef&);
279  //! Disallow construction from non-const array
280  template<SizeType N>
281  GenericStringRef(CharType (&str)[N]) /* = delete */;
282 };
283 
284 //! Mark a character pointer as constant string
285 /*! Mark a plain character pointer as a "string literal". This function
286  can be used to avoid copying a character string to be referenced as a
287  value in a JSON GenericValue object, if the string's lifetime is known
288  to be valid long enough.
289  \tparam CharType Character type of the string
290  \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
291  \return GenericStringRef string reference object
292  \relatesalso GenericStringRef
293 
294  \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember
295 */
296 template<typename CharType>
297 inline GenericStringRef<CharType> StringRef(const CharType* str) {
298  return GenericStringRef<CharType>(str, internal::StrLen(str));
299 }
300 
301 //! Mark a character pointer as constant string
302 /*! Mark a plain character pointer as a "string literal". This function
303  can be used to avoid copying a character string to be referenced as a
304  value in a JSON GenericValue object, if the string's lifetime is known
305  to be valid long enough.
306 
307  This version has better performance with supplied length, and also
308  supports string containing null characters.
309 
310  \tparam CharType character type of the string
311  \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
312  \param length The length of source string.
313  \return GenericStringRef string reference object
314  \relatesalso GenericStringRef
315 */
316 template<typename CharType>
317 inline GenericStringRef<CharType> StringRef(const CharType* str, size_t length) {
318  return GenericStringRef<CharType>(str, SizeType(length));
319 }
320 
321 ///////////////////////////////////////////////////////////////////////////////
322 // GenericValue
323 
324 //! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
325 /*!
326  A JSON value can be one of 7 types. This class is a variant type supporting
327  these types.
328 
329  Use the Value if UTF8 and default allocator
330 
331  \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
332  \tparam Allocator Allocator type for allocating memory of object, array and string.
333 */
334 #pragma pack (push, 4)
335 template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
336 class GenericValue {
337 public:
338  //! Name-value pair in an object.
340  typedef Encoding EncodingType; //!< Encoding type from template parameter.
341  typedef Allocator AllocatorType; //!< Allocator type from template parameter.
342  typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
343  typedef GenericStringRef<Ch> StringRefType; //!< Reference to a constant string
344  typedef typename GenericMemberIterator<false,Encoding,Allocator>::Iterator MemberIterator; //!< Member iterator for iterating in object.
345  typedef typename GenericMemberIterator<true,Encoding,Allocator>::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object.
346  typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
347  typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
348 
349  //!@name Constructors and destructor.
350  //@{
351 
352  //! Default constructor creates a null value.
353  GenericValue() : data_(), flags_(kNullFlag) {}
354 
355 private:
356  //! Copy constructor is not permitted.
357  GenericValue(const GenericValue& rhs);
358 
359 public:
360 
361  //! Constructor with JSON value type.
362  /*! This creates a Value of specified type with default content.
363  \param type Type of the value.
364  \note Default content for number is zero.
365  */
366  GenericValue(Type type) : data_(), flags_() {
367  static const unsigned defaultFlags[7] = {
368  kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kConstStringFlag,
369  kNumberAnyFlag
370  };
371  RAPIDJSON_ASSERT(type <= kNumberType);
372  flags_ = defaultFlags[type];
373  }
374 
375  //! Explicit copy constructor (with allocator)
376  /*! Creates a copy of a Value by using the given Allocator
377  \tparam SourceAllocator allocator of \c rhs
378  \param rhs Value to copy from (read-only)
379  \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator().
380  \see CopyFrom()
381  */
382  template< typename SourceAllocator >
384 
385  //! Constructor for boolean value.
386  /*! \param b Boolean value
387  \note This constructor is limited to \em real boolean values and rejects
388  implicitly converted types like arbitrary pointers. Use an explicit cast
389  to \c bool, if you want to construct a boolean JSON value in such cases.
390  */
391 #ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen
392  template <typename T>
393  explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame<T,bool>)))
394 #else
395  explicit GenericValue(bool b)
396 #endif
397  : data_(), flags_(b ? kTrueFlag : kFalseFlag) {}
398 
399  //! Constructor for int value.
400  explicit GenericValue(int i) : data_(), flags_(kNumberIntFlag) {
401  data_.n.i64 = i;
402  if (i >= 0)
403  flags_ |= kUintFlag | kUint64Flag;
404  }
405 
406  //! Constructor for unsigned value.
407  explicit GenericValue(unsigned u) : data_(), flags_(kNumberUintFlag) {
408  data_.n.u64 = u;
409  if (!(u & 0x80000000))
410  flags_ |= kIntFlag | kInt64Flag;
411  }
412 
413  //! Constructor for int64_t value.
414  explicit GenericValue(int64_t i64) : data_(), flags_(kNumberInt64Flag) {
415  data_.n.i64 = i64;
416  if (i64 >= 0) {
417  flags_ |= kNumberUint64Flag;
418  if (!(static_cast<uint64_t>(i64) & UINT64_C(0xFFFFFFFF00000000)))
419  flags_ |= kUintFlag;
420  if (!(static_cast<uint64_t>(i64) & UINT64_C(0xFFFFFFFF80000000)))
421  flags_ |= kIntFlag;
422  }
423  else if (i64 >= INT64_C(-2147483648))
424  flags_ |= kIntFlag;
425  }
426 
427  //! Constructor for uint64_t value.
428  explicit GenericValue(uint64_t u64) : data_(), flags_(kNumberUint64Flag) {
429  data_.n.u64 = u64;
430  if (!(u64 & UINT64_C(0x8000000000000000)))
431  flags_ |= kInt64Flag;
432  if (!(u64 & UINT64_C(0xFFFFFFFF00000000)))
433  flags_ |= kUintFlag;
434  if (!(u64 & UINT64_C(0xFFFFFFFF80000000)))
435  flags_ |= kIntFlag;
436  }
437 
438  //! Constructor for double value.
439  explicit GenericValue(double d) : data_(), flags_(kNumberDoubleFlag) { data_.n.d = d; }
440 
441  //! Constructor for constant string (i.e. do not make a copy of string)
442  GenericValue(const Ch* s, SizeType length) : data_(), flags_() { SetStringRaw(StringRef(s, length)); }
443 
444  //! Constructor for constant string (i.e. do not make a copy of string)
445  explicit GenericValue(StringRefType s) : data_(), flags_() { SetStringRaw(s); }
446 
447  //! Constructor for copy-string (i.e. do make a copy of string)
448  GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_(), flags_() { SetStringRaw(StringRef(s, length), allocator); }
449 
450  //! Constructor for copy-string (i.e. do make a copy of string)
451  GenericValue(const Ch*s, Allocator& allocator) : data_(), flags_() { SetStringRaw(StringRef(s), allocator); }
452 
453  //! Destructor.
454  /*! Need to destruct elements of array, members of object, or copy-string.
455  */
457  if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
458  switch(flags_) {
459  case kArrayFlag:
460  for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
461  v->~GenericValue();
462  Allocator::Free(data_.a.elements);
463  break;
464 
465  case kObjectFlag:
466  for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
467  m->name.~GenericValue();
468  m->value.~GenericValue();
469  }
470  Allocator::Free(data_.o.members);
471  break;
472 
473  case kCopyStringFlag:
474  Allocator::Free(const_cast<Ch*>(data_.s.str));
475  break;
476 
477  default:
478  break; // Do nothing for other types.
479  }
480  }
481  }
482 
483  //@}
484 
485  //!@name Assignment operators
486  //@{
487 
488  //! Assignment with move semantics.
489  /*! \param rhs Source of the assignment. It will become a null value after assignment.
490  */
492  RAPIDJSON_ASSERT(this != &rhs);
493  this->~GenericValue();
494  RawAssign(rhs);
495  return *this;
496  }
497 
498  //! Assignment of constant string reference (no copy)
499  /*! \param str Constant string reference to be assigned
500  \note This overload is needed to avoid clashes with the generic primitive type assignment overload below.
501  \see GenericStringRef, operator=(T)
502  */
504  GenericValue s(str);
505  return *this = s;
506  }
507 
508  //! Assignment with primitive types.
509  /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
510  \param value The value to be assigned.
511 
512  \note The source type \c T explicitly disallows all pointer types,
513  especially (\c const) \ref Ch*. This helps avoiding implicitly
514  referencing character strings with insufficient lifetime, use
515  \ref SetString(const Ch*, Allocator&) (for copying) or
516  \ref StringRef() (to explicitly mark the pointer as constant) instead.
517  All other pointer types would implicitly convert to \c bool,
518  use \ref SetBool() instead.
519  */
520  template <typename T>
521  RAPIDJSON_DISABLEIF_RETURN(internal::IsPointer<T>,GenericValue&)
522  operator=(T value) {
523  GenericValue v(value);
524  return *this = v;
525  }
526 
527  //! Deep-copy assignment from Value
528  /*! Assigns a \b copy of the Value to the current Value object
529  \tparam SourceAllocator Allocator type of \c rhs
530  \param rhs Value to copy from (read-only)
531  \param allocator Allocator to use for copying
532  */
533  template <typename SourceAllocator>
535  RAPIDJSON_ASSERT((void*)this != (void const*)&rhs);
536  this->~GenericValue();
537  new (this) GenericValue(rhs,allocator);
538  return *this;
539  }
540 
541  //! Exchange the contents of this value with those of other.
542  /*!
543  \param other Another value.
544  \note Constant complexity.
545  */
547  GenericValue temp;
548  temp.RawAssign(*this);
549  RawAssign(other);
550  other.RawAssign(temp);
551  return *this;
552  }
553 
554  //! Prepare Value for move semantics
555  /*! \return *this */
556  GenericValue& Move() { return *this; }
557  //@}
558 
559  //!@name Type
560  //@{
561 
562  Type GetType() const { return static_cast<Type>(flags_ & kTypeMask); }
563  bool IsNull() const { return flags_ == kNullFlag; }
564  bool IsFalse() const { return flags_ == kFalseFlag; }
565  bool IsTrue() const { return flags_ == kTrueFlag; }
566  bool IsBool() const { return (flags_ & kBoolFlag) != 0; }
567  bool IsObject() const { return flags_ == kObjectFlag; }
568  bool IsArray() const { return flags_ == kArrayFlag; }
569  bool IsNumber() const { return (flags_ & kNumberFlag) != 0; }
570  bool IsInt() const { return (flags_ & kIntFlag) != 0; }
571  bool IsUint() const { return (flags_ & kUintFlag) != 0; }
572  bool IsInt64() const { return (flags_ & kInt64Flag) != 0; }
573  bool IsUint64() const { return (flags_ & kUint64Flag) != 0; }
574  bool IsDouble() const { return (flags_ & kDoubleFlag) != 0; }
575  bool IsString() const { return (flags_ & kStringFlag) != 0; }
576 
577  //@}
578 
579  //!@name Null
580  //@{
581 
582  GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
583 
584  //@}
585 
586  //!@name Bool
587  //@{
588 
589  bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return flags_ == kTrueFlag; }
590  //!< Set boolean value
591  /*! \post IsBool() == true */
592  GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
593 
594  //@}
595 
596  //!@name Object
597  //@{
598 
599  //! Set this value as an empty object.
600  /*! \post IsObject() == true */
601  GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
602 
603  //! Get the value associated with the name.
604  /*!
605  \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
606  Since 0.2, if the name is not correct, it will assert.
607  If user is unsure whether a member exists, user should use HasMember() first.
608  A better approach is to use the now public FindMember().
609  */
610  GenericValue& operator[](const Ch* name) {
611  GenericValue n(StringRef(name));
612  return (*this)[n];
613  }
614  const GenericValue& operator[](const Ch* name) const { return const_cast<GenericValue&>(*this)[name]; }
615 
616  // This version is faster because it does not need a StrLen().
617  // It can also handle string with null character.
618  GenericValue& operator[](const GenericValue& name) {
619  MemberIterator member = FindMember(name);
620  if (member != MemberEnd())
621  return member->value;
622  else {
623  RAPIDJSON_ASSERT(false); // see above note
624  static GenericValue NullValue;
625  return NullValue;
626  }
627  }
628  const GenericValue& operator[](const GenericValue& name) const { return const_cast<GenericValue&>(*this)[name]; }
629 
630  //! Const member iterator
631  /*! \pre IsObject() == true */
632  ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(data_.o.members); }
633  //! Const \em past-the-end member iterator
634  /*! \pre IsObject() == true */
635  ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(data_.o.members + data_.o.size); }
636  //! Member iterator
637  /*! \pre IsObject() == true */
638  MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(data_.o.members); }
639  //! \em Past-the-end member iterator
640  /*! \pre IsObject() == true */
641  MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(data_.o.members + data_.o.size); }
642 
643  //! Check whether a member exists in the object.
644  /*!
645  \note It is better to use FindMember() directly if you need the obtain the value as well.
646  */
647  bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); }
648 
649  // This version is faster because it does not need a StrLen().
650  // It can also handle string with null character.
651  bool HasMember(const GenericValue& name) const { return FindMember(name) != MemberEnd(); }
652 
653  //! Find member by name.
654  /*!
655  \pre IsObject() == true
656  \return Iterator to member, if it exists.
657  Otherwise returns \ref MemberEnd().
658 
659  \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
660  the requested member doesn't exist. For consistency with e.g.
661  \c std::map, this has been changed to MemberEnd() now.
662  */
663  MemberIterator FindMember(const Ch* name) {
664  GenericValue n(StringRef(name));
665  return FindMember(n);
666  }
667 
668  ConstMemberIterator FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
669 
670  // This version is faster because it does not need a StrLen().
671  // It can also handle string with null character.
672  MemberIterator FindMember(const GenericValue& name) {
673  RAPIDJSON_ASSERT(IsObject());
674  RAPIDJSON_ASSERT(name.IsString());
675  SizeType len = name.data_.s.length;
676  MemberIterator member = MemberBegin();
677  for ( ; member != MemberEnd(); ++member)
678  if (member->name.data_.s.length == len && memcmp(member->name.data_.s.str, name.data_.s.str, len * sizeof(Ch)) == 0)
679  break;
680  return member;
681  }
682  ConstMemberIterator FindMember(const GenericValue& name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
683 
684  //! Add a member (name-value pair) to the object.
685  /*! \param name A string value as name of member.
686  \param value Value of any type.
687  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
688  \return The value itself for fluent API.
689  \note The ownership of \c name and \c value will be transferred to this object on success.
690  \pre IsObject() && name.IsString()
691  \post name.IsNull() && value.IsNull()
692  */
694  RAPIDJSON_ASSERT(IsObject());
695  RAPIDJSON_ASSERT(name.IsString());
696 
697  Object& o = data_.o;
698  if (o.size >= o.capacity) {
699  if (o.capacity == 0) {
700  o.capacity = kDefaultObjectCapacity;
701  o.members = reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member)));
702  }
703  else {
704  SizeType oldCapacity = o.capacity;
705  o.capacity *= 2;
706  o.members = reinterpret_cast<Member*>(allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member)));
707  }
708  }
709  o.members[o.size].name.RawAssign(name);
710  o.members[o.size].value.RawAssign(value);
711  o.size++;
712  return *this;
713  }
714 
715  //! Add a member (name-value pair) to the object.
716  /*! \param name A constant string reference as name of member.
717  \param value Value of any type.
718  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
719  \return The value itself for fluent API.
720  \note The ownership of \c value will be transferred to this object on success.
721  \pre IsObject()
722  \post value.IsNull()
723  */
725  GenericValue n(name);
726  return AddMember(n, value, allocator);
727  }
728 
729  //! Add a constant string value as member (name-value pair) to the object.
730  /*! \param name A constant string reference as name of member.
731  \param value constant string reference as value of member.
732  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
733  \return The value itself for fluent API.
734  \pre IsObject()
735  \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below.
736  */
738  GenericValue v(value);
739  return AddMember(name, v, allocator);
740  }
741 
742  //! Add any primitive value as member (name-value pair) to the object.
743  /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
744  \param name A constant string reference as name of member.
745  \param value Value of primitive type \c T as value of member
746  \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
747  \return The value itself for fluent API.
748  \pre IsObject()
749 
750  \note The source type \c T explicitly disallows all pointer types,
751  especially (\c const) \ref Ch*. This helps avoiding implicitly
752  referencing character strings with insufficient lifetime, use
753  \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
754  AddMember(StringRefType, StringRefType, Allocator&).
755  All other pointer types would implicitly convert to \c bool,
756  use an explicit cast instead, if needed.
757  */
758  template <typename T>
759  RAPIDJSON_DISABLEIF_RETURN(internal::IsPointer<T>,GenericValue&)
760  AddMember(StringRefType name, T value, Allocator& allocator) {
761  GenericValue n(name);
762  GenericValue v(value);
763  return AddMember(n, v, allocator);
764  }
765 
766  //! Remove a member in object by its name.
767  /*! \param name Name of member to be removed.
768  \return Whether the member existed.
769  \note Removing member is implemented by moving the last member. So the ordering of members is changed.
770  */
771  bool RemoveMember(const Ch* name) {
772  GenericValue n(StringRef(name));
773  return RemoveMember(n);
774  }
775 
776  bool RemoveMember(const GenericValue& name) {
777  MemberIterator m = FindMember(name);
778  if (m != MemberEnd()) {
779  RemoveMember(m);
780  return true;
781  }
782  else
783  return false;
784  }
785 
786  //! Remove a member in object by iterator.
787  /*! \param m member iterator (obtained by FindMember() or MemberBegin()).
788  \return the new iterator after removal.
789  \note Removing member is implemented by moving the last member. So the ordering of members is changed.
790  */
792  RAPIDJSON_ASSERT(IsObject());
793  RAPIDJSON_ASSERT(data_.o.size > 0);
794  RAPIDJSON_ASSERT(data_.o.members != 0);
795  RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd());
796 
797  MemberIterator last(data_.o.members + (data_.o.size - 1));
798  if (data_.o.size > 1 && m != last) {
799  // Move the last one to this place
800  m->name = last->name;
801  m->value = last->value;
802  }
803  else {
804  // Only one left, just destroy
805  m->name.~GenericValue();
806  m->value.~GenericValue();
807  }
808  --data_.o.size;
809  return m;
810  }
811 
812  //@}
813 
814  //!@name Array
815  //@{
816 
817  //! Set this value as an empty array.
818  /*! \post IsArray == true */
819  GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
820 
821  //! Get the number of elements in array.
822  SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
823 
824  //! Get the capacity of array.
825  SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
826 
827  //! Check whether the array is empty.
828  bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
829 
830  //! Remove all elements in the array.
831  /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
832  */
833  void Clear() {
834  RAPIDJSON_ASSERT(IsArray());
835  for (SizeType i = 0; i < data_.a.size; ++i)
836  data_.a.elements[i].~GenericValue();
837  data_.a.size = 0;
838  }
839 
840  //! Get an element from array by index.
841  /*! \param index Zero-based index of element.
842 \code
843 Value a(kArrayType);
844 a.PushBack(123);
845 int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
846 int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
847 int z = a[0u].GetInt(); // This works too.
848 \endcode
849  */
851  RAPIDJSON_ASSERT(IsArray());
852  RAPIDJSON_ASSERT(index < data_.a.size);
853  return data_.a.elements[index];
854  }
855  const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; }
856 
857  //! Element iterator
858  ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements; }
859  ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements + data_.a.size; }
860  ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); }
861  ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); }
862 
863  //! Request the array to have enough capacity to store elements.
864  /*! \param newCapacity The capacity that the array at least need to have.
865  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
866  \return The value itself for fluent API.
867  */
868  GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
869  RAPIDJSON_ASSERT(IsArray());
870  if (newCapacity > data_.a.capacity) {
871  data_.a.elements = (GenericValue*)allocator.Realloc(data_.a.elements, data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue));
872  data_.a.capacity = newCapacity;
873  }
874  return *this;
875  }
876 
877  //! Append a GenericValue at the end of the array.
878  /*! \param value Value to be appended.
879  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
880  \pre IsArray() == true
881  \post value.IsNull() == true
882  \return The value itself for fluent API.
883  \note The ownership of \c value will be transferred to this array on success.
884  \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
885  */
887  RAPIDJSON_ASSERT(IsArray());
888  if (data_.a.size >= data_.a.capacity)
889  Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : data_.a.capacity * 2, allocator);
890  data_.a.elements[data_.a.size++].RawAssign(value);
891  return *this;
892  }
893 
894  //! Append a constant string reference at the end of the array.
895  /*! \param value Constant string reference to be appended.
896  \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator().
897  \pre IsArray() == true
898  \return The value itself for fluent API.
899  \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
900  \see GenericStringRef
901  */
903  return (*this).template PushBack<StringRefType>(value, allocator);
904  }
905 
906  //! Append a primitive value at the end of the array(.)
907  /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
908  \param value Value of primitive type T to be appended.
909  \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
910  \pre IsArray() == true
911  \return The value itself for fluent API.
912  \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
913 
914  \note The source type \c T explicitly disallows all pointer types,
915  especially (\c const) \ref Ch*. This helps avoiding implicitly
916  referencing character strings with insufficient lifetime, use
917  \ref PushBack(GenericValue&, Allocator&) or \ref
918  PushBack(StringRefType, Allocator&).
919  All other pointer types would implicitly convert to \c bool,
920  use an explicit cast instead, if needed.
921  */
922  template <typename T>
923  RAPIDJSON_DISABLEIF_RETURN(internal::IsPointer<T>,GenericValue&)
924  PushBack(T value, Allocator& allocator) {
925  GenericValue v(value);
926  return PushBack(v, allocator);
927  }
928 
929  //! Remove the last element in the array.
931  RAPIDJSON_ASSERT(IsArray());
933  data_.a.elements[--data_.a.size].~GenericValue();
934  return *this;
935  }
936  //@}
937 
938  //!@name Number
939  //@{
940 
941  int GetInt() const { RAPIDJSON_ASSERT(flags_ & kIntFlag); return data_.n.i.i; }
942  unsigned GetUint() const { RAPIDJSON_ASSERT(flags_ & kUintFlag); return data_.n.u.u; }
943  int64_t GetInt64() const { RAPIDJSON_ASSERT(flags_ & kInt64Flag); return data_.n.i64; }
944  uint64_t GetUint64() const { RAPIDJSON_ASSERT(flags_ & kUint64Flag); return data_.n.u64; }
945 
946  double GetDouble() const {
947  RAPIDJSON_ASSERT(IsNumber());
948  if ((flags_ & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
949  if ((flags_ & kIntFlag) != 0) return data_.n.i.i; // int -> double
950  if ((flags_ & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
951  if ((flags_ & kInt64Flag) != 0) return (double)data_.n.i64; // int64_t -> double (may lose precision)
952  RAPIDJSON_ASSERT((flags_ & kUint64Flag) != 0); return (double)data_.n.u64; // uint64_t -> double (may lose precision)
953  }
954 
955  GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
956  GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
957  GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
958  GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
959  GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
960 
961  //@}
962 
963  //!@name String
964  //@{
965 
966  const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return data_.s.str; }
967 
968  //! Get the length of string.
969  /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
970  */
971  SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return data_.s.length; }
972 
973  //! Set this value as a string without copying source string.
974  /*! This version has better performance with supplied length, and also support string containing null character.
975  \param s source string pointer.
976  \param length The length of source string, excluding the trailing null terminator.
977  \return The value itself for fluent API.
978  \post IsString() == true && GetString() == s && GetStringLength() == length
979  \see SetString(StringRefType)
980  */
981  GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); }
982 
983  //! Set this value as a string without copying source string.
984  /*! \param s source string reference
985  \return The value itself for fluent API.
986  \post IsString() == true && GetString() == s && GetStringLength() == s.length
987  */
988  GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; }
989 
990  //! Set this value as a string by copying from source string.
991  /*! This version has better performance with supplied length, and also support string containing null character.
992  \param s source string.
993  \param length The length of source string, excluding the trailing null terminator.
994  \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
995  \return The value itself for fluent API.
996  \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
997  */
998  GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(StringRef(s, length), allocator); return *this; }
999 
1000  //! Set this value as a string by copying from source string.
1001  /*! \param s source string.
1002  \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
1003  \return The value itself for fluent API.
1004  \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
1005  */
1006  GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(s, internal::StrLen(s), allocator); }
1007 
1008  //@}
1009 
1010  //! Generate events of this value to a Handler.
1011  /*! This function adopts the GoF visitor pattern.
1012  Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
1013  It can also be used to deep clone this value via GenericDocument, which is also a Handler.
1014  \tparam Handler type of handler.
1015  \param handler An object implementing concept Handler.
1016  */
1017  template <typename Handler>
1018  bool Accept(Handler& handler) const {
1019  switch(GetType()) {
1020  case kNullType: return handler.Null();
1021  case kFalseType: return handler.Bool(false);
1022  case kTrueType: return handler.Bool(true);
1023 
1024  case kObjectType:
1025  if (!handler.StartObject())
1026  return false;
1027  for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
1028  if (!handler.String(m->name.data_.s.str, m->name.data_.s.length, (m->name.flags_ & kCopyFlag) != 0))
1029  return false;
1030  if (!m->value.Accept(handler))
1031  return false;
1032  }
1033  return handler.EndObject(data_.o.size);
1034 
1035  case kArrayType:
1036  if (!handler.StartArray())
1037  return false;
1038  for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
1039  if (!v->Accept(handler))
1040  return false;
1041  return handler.EndArray(data_.a.size);
1042 
1043  case kStringType:
1044  return handler.String(data_.s.str, data_.s.length, (flags_ & kCopyFlag) != 0);
1045 
1046  case kNumberType:
1047  if (IsInt()) return handler.Int(data_.n.i.i);
1048  else if (IsUint()) return handler.Uint(data_.n.u.u);
1049  else if (IsInt64()) return handler.Int64(data_.n.i64);
1050  else if (IsUint64()) return handler.Uint64(data_.n.u64);
1051  else return handler.Double(data_.n.d);
1052 
1053  default:
1054  RAPIDJSON_ASSERT(false);
1055  }
1056  return false;
1057  }
1058 
1059 private:
1060  template <typename, typename>
1061  friend class GenericDocument;
1062 
1063  enum {
1064  kBoolFlag = 0x100,
1065  kNumberFlag = 0x200,
1066  kIntFlag = 0x400,
1067  kUintFlag = 0x800,
1068  kInt64Flag = 0x1000,
1069  kUint64Flag = 0x2000,
1070  kDoubleFlag = 0x4000,
1071  kStringFlag = 0x100000,
1072  kCopyFlag = 0x200000,
1073 
1074  // Initial flags of different types.
1075  kNullFlag = kNullType,
1076  kTrueFlag = kTrueType | kBoolFlag,
1077  kFalseFlag = kFalseType | kBoolFlag,
1078  kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
1079  kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
1080  kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
1081  kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
1082  kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
1083  kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag,
1084  kConstStringFlag = kStringType | kStringFlag,
1085  kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
1086  kObjectFlag = kObjectType,
1087  kArrayFlag = kArrayType,
1088 
1089  kTypeMask = 0xFF // bitwise-and with mask of 0xFF can be optimized by compiler
1090  };
1091 
1092  static const SizeType kDefaultArrayCapacity = 16;
1093  static const SizeType kDefaultObjectCapacity = 16;
1094 
1095  struct String {
1096  const Ch* str;
1097  SizeType length;
1098  unsigned hashcode; //!< reserved
1099  }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
1100 
1101  // By using proper binary layout, retrieval of different integer types do not need conversions.
1102  union Number {
1103 #if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN
1104  struct I {
1105  int i;
1106  char padding[4];
1107  }i;
1108  struct U {
1109  unsigned u;
1110  char padding2[4];
1111  }u;
1112 #else
1113  struct I {
1114  char padding[4];
1115  int i;
1116  }i;
1117  struct U {
1118  char padding2[4];
1119  unsigned u;
1120  }u;
1121 #endif
1122  int64_t i64;
1123  uint64_t u64;
1124  double d;
1125  }; // 8 bytes
1126 
1127  struct Object {
1128  Member* members;
1129  SizeType size;
1130  SizeType capacity;
1131  }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
1132 
1133  struct Array {
1134  GenericValue* elements;
1135  SizeType size;
1136  SizeType capacity;
1137  }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
1138 
1139  union Data {
1140  String s;
1141  Number n;
1142  Object o;
1143  Array a;
1144  }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
1145 
1146  // Initialize this value as array with initial data, without calling destructor.
1147  void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) {
1148  flags_ = kArrayFlag;
1149  data_.a.elements = (GenericValue*)allocator.Malloc(count * sizeof(GenericValue));
1150  memcpy(data_.a.elements, values, count * sizeof(GenericValue));
1151  data_.a.size = data_.a.capacity = count;
1152  }
1153 
1154  //! Initialize this value as object with initial data, without calling destructor.
1155  void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
1156  flags_ = kObjectFlag;
1157  data_.o.members = (Member*)allocator.Malloc(count * sizeof(Member));
1158  memcpy(data_.o.members, members, count * sizeof(Member));
1159  data_.o.size = data_.o.capacity = count;
1160  }
1161 
1162  //! Initialize this value as constant string, without calling destructor.
1163  void SetStringRaw(StringRefType s) {
1164  flags_ = kConstStringFlag;
1165  data_.s.str = s;
1166  data_.s.length = s.length;
1167  }
1168 
1169  //! Initialize this value as copy string with initial data, without calling destructor.
1170  void SetStringRaw(StringRefType s, Allocator& allocator) {
1171  flags_ = kCopyStringFlag;
1172  data_.s.str = (Ch *)allocator.Malloc((s.length + 1) * sizeof(Ch));
1173  data_.s.length = s.length;
1174  memcpy(const_cast<Ch*>(data_.s.str), s, s.length * sizeof(Ch));
1175  const_cast<Ch*>(data_.s.str)[s.length] = '\0';
1176  }
1177 
1178  //! Assignment without calling destructor
1179  void RawAssign(GenericValue& rhs) {
1180  data_ = rhs.data_;
1181  flags_ = rhs.flags_;
1182  rhs.flags_ = kNullFlag;
1183  }
1184 
1185  Data data_;
1186  unsigned flags_;
1187 };
1188 #pragma pack (pop)
1189 
1190 //! GenericValue with UTF8 encoding
1192 
1193 ///////////////////////////////////////////////////////////////////////////////
1194 // GenericDocument
1195 
1196 //! A document for parsing JSON text as DOM.
1197 /*!
1198  \note implements Handler concept
1199  \tparam Encoding encoding for both parsing and string storage.
1200  \tparam Allocator allocator for allocating memory for the DOM, and the stack during parsing.
1201  \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructors. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue.
1202 */
1203 template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
1204 class GenericDocument : public GenericValue<Encoding, Allocator> {
1205 public:
1206  typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
1207  typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.
1208  typedef Allocator AllocatorType; //!< Allocator type from template parameter.
1209 
1210  //! Constructor
1211  /*! \param allocator Optional allocator for allocating stack memory.
1212  \param stackCapacity Initial capacity of stack in bytes.
1213  */
1214  GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(allocator, stackCapacity), parseResult_() {}
1215 
1216  //!@name Parse from stream
1217  //!@{
1218 
1219  //! Parse JSON text from an input stream (with Encoding conversion)
1220  /*! \tparam parseFlags Combination of \ref ParseFlag.
1221  \tparam SourceEncoding Encoding of input stream
1222  \tparam InputStream Type of input stream, implementing Stream concept
1223  \param is Input stream to be parsed.
1224  \return The document itself for fluent API.
1225  */
1226  template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
1227  GenericDocument& ParseStream(InputStream& is) {
1228  ValueType::SetNull(); // Remove existing root if exist
1230  ClearStackOnExit scope(*this);
1231  parseResult_ = reader.template Parse<parseFlags>(is, *this);
1232  if (parseResult_) {
1233  RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
1234  this->RawAssign(*stack_.template Pop<ValueType>(1)); // Add this-> to prevent issue 13.
1235  }
1236  return *this;
1237  }
1238 
1239  //! Parse JSON text from an input stream
1240  /*! \tparam parseFlags Combination of \ref ParseFlag.
1241  \tparam InputStream Type of input stream, implementing Stream concept
1242  \param is Input stream to be parsed.
1243  \return The document itself for fluent API.
1244  */
1245  template <unsigned parseFlags, typename InputStream>
1246  GenericDocument& ParseStream(InputStream& is) {
1247  return ParseStream<parseFlags,Encoding,InputStream>(is);
1248  }
1249 
1250  //! Parse JSON text from an input stream (with \ref kParseDefaultFlags)
1251  /*! \tparam InputStream Type of input stream, implementing Stream concept
1252  \param is Input stream to be parsed.
1253  \return The document itself for fluent API.
1254  */
1255  template <typename InputStream>
1256  GenericDocument& ParseStream(InputStream& is) {
1257  return ParseStream<kParseDefaultFlags, Encoding, InputStream>(is);
1258  }
1259  //!@}
1260 
1261  //!@name Parse in-place from mutable string
1262  //!@{
1263 
1264  //! Parse JSON text from a mutable string (with Encoding conversion)
1265  /*! \tparam parseFlags Combination of \ref ParseFlag.
1266  \tparam SourceEncoding Transcoding from input Encoding
1267  \param str Mutable zero-terminated string to be parsed.
1268  \return The document itself for fluent API.
1269  */
1270  template <unsigned parseFlags, typename SourceEncoding>
1273  return ParseStream<parseFlags | kParseInsituFlag, SourceEncoding>(s);
1274  }
1275 
1276  //! Parse JSON text from a mutable string
1277  /*! \tparam parseFlags Combination of \ref ParseFlag.
1278  \param str Mutable zero-terminated string to be parsed.
1279  \return The document itself for fluent API.
1280  */
1281  template <unsigned parseFlags>
1283  return ParseInsitu<parseFlags, Encoding>(str);
1284  }
1285 
1286  //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags)
1287  /*! \param str Mutable zero-terminated string to be parsed.
1288  \return The document itself for fluent API.
1289  */
1291  return ParseInsitu<kParseDefaultFlags, Encoding>(str);
1292  }
1293  //!@}
1294 
1295  //!@name Parse from read-only string
1296  //!@{
1297 
1298  //! Parse JSON text from a read-only string (with Encoding conversion)
1299  /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
1300  \tparam SourceEncoding Transcoding from input Encoding
1301  \param str Read-only zero-terminated string to be parsed.
1302  */
1303  template <unsigned parseFlags, typename SourceEncoding>
1304  GenericDocument& Parse(const Ch* str) {
1305  RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
1307  return ParseStream<parseFlags, SourceEncoding>(s);
1308  }
1309 
1310  //! Parse JSON text from a read-only string
1311  /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
1312  \param str Read-only zero-terminated string to be parsed.
1313  */
1314  template <unsigned parseFlags>
1315  GenericDocument& Parse(const Ch* str) {
1316  return Parse<parseFlags, Encoding>(str);
1317  }
1318 
1319  //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags)
1320  /*! \param str Read-only zero-terminated string to be parsed.
1321  */
1322  GenericDocument& Parse(const Ch* str) {
1323  return Parse<kParseDefaultFlags>(str);
1324  }
1325  //!@}
1326 
1327  //!@name Handling parse errors
1328  //!@{
1329 
1330  //! Whether a parse error has occured in the last parsing.
1331  bool HasParseError() const { return parseResult_.IsError(); }
1332 
1333  //! Get the \ref ParseErrorCode of last parsing.
1334  ParseErrorCode GetParseError() const { return parseResult_.Code(); }
1335 
1336  //! Get the position of last parsing error in input, 0 otherwise.
1337  size_t GetErrorOffset() const { return parseResult_.Offset(); }
1338 
1339  //!@}
1340 
1341  //! Get the allocator of this document.
1342  Allocator& GetAllocator() { return stack_.GetAllocator(); }
1343 
1344  //! Get the capacity of stack in bytes.
1345  size_t GetStackCapacity() const { return stack_.GetCapacity(); }
1346 
1347 private:
1348  // clear stack on any exit from ParseStream, e.g. due to exception
1349  struct ClearStackOnExit {
1350  explicit ClearStackOnExit(GenericDocument& d) : d_(d) {}
1351  ~ClearStackOnExit() { d_.ClearStack(); }
1352  private:
1353  ClearStackOnExit(const ClearStackOnExit&);
1354  ClearStackOnExit& operator=(const ClearStackOnExit&);
1355  GenericDocument& d_;
1356  };
1357 
1358  // callers of the following private Handler functions
1359  template <typename,typename,typename> friend class GenericReader; // for parsing
1360  friend class GenericValue<Encoding,Allocator>; // for deep copying
1361 
1362  // Implementation of Handler
1363  bool Null() { new (stack_.template Push<ValueType>()) ValueType(); return true; }
1364  bool Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); return true; }
1365  bool Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
1366  bool Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
1367  bool Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
1368  bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
1369  bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; }
1370 
1371  bool String(const Ch* str, SizeType length, bool copy) {
1372  if (copy)
1373  new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
1374  else
1375  new (stack_.template Push<ValueType>()) ValueType(str, length);
1376  return true;
1377  }
1378 
1379  bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; }
1380 
1381  bool EndObject(SizeType memberCount) {
1382  typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount);
1383  stack_.template Top<ValueType>()->SetObjectRaw(members, (SizeType)memberCount, GetAllocator());
1384  return true;
1385  }
1386 
1387  bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; }
1388 
1389  bool EndArray(SizeType elementCount) {
1390  ValueType* elements = stack_.template Pop<ValueType>(elementCount);
1391  stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator());
1392  return true;
1393  }
1394 
1395 private:
1396  //! Prohibit assignment
1397  GenericDocument& operator=(const GenericDocument&);
1398 
1399  void ClearStack() {
1400  if (Allocator::kNeedFree)
1401  while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects)
1402  (stack_.template Pop<ValueType>(1))->~ValueType();
1403  else
1404  stack_.Clear();
1405  }
1406 
1407  static const size_t kDefaultStackCapacity = 1024;
1408  internal::Stack<Allocator> stack_;
1409  ParseResult parseResult_;
1410 };
1411 
1412 //! GenericDocument with UTF8 encoding
1414 
1415 // defined here due to the dependency on GenericDocument
1416 template <typename Encoding, typename Allocator>
1417 template <typename SourceAllocator>
1418 inline
1420 {
1422  rhs.Accept(d);
1423  RawAssign(*d.stack_.template Pop<GenericValue>(1));
1424 }
1425 
1426 } // namespace rapidjson
1427 
1428 #if defined(_MSC_VER) || defined(__GNUC__)
1429 RAPIDJSON_DIAG_POP
1430 #endif
1431 
1432 #endif // RAPIDJSON_DOCUMENT_H_