Debian Codegraph @

include/json/value.h

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2 // Distributed under MIT license, or public domain if desired and
3 // recognized in your jurisdiction.
4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5
6 #ifndef JSON_VALUE_H_INCLUDED
7 #define JSON_VALUE_H_INCLUDED
8
9 #if !defined(JSON_IS_AMALGAMATION)
10 #include "forwards.h"
11 #endif // if !defined(JSON_IS_AMALGAMATION)
12
13 // Conditional NORETURN attribute on the throw functions would:
14 // a) suppress false positives from static code analysis
15 // b) possibly improve optimization opportunities.
16 #if !defined(JSONCPP_NORETURN)
17 #if defined(_MSC_VER) && _MSC_VER == 1800
18 #define JSONCPP_NORETURN __declspec(noreturn)
19 #else
20 #define JSONCPP_NORETURN [[noreturn]]
21 #endif
22 #endif
23
24 // Support for '= delete' with template declarations was a late addition
25 // to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
26 // even though these declare themselves to be c++11 compilers.
27 #if !defined(JSONCPP_TEMPLATE_DELETE)
28 #if defined(__clang__) && defined(__apple_build_version__)
29 #if __apple_build_version__ <= 8000042
30 #define JSONCPP_TEMPLATE_DELETE
31 #endif
32 #elif defined(__clang__)
33 #if __clang_major__ == 3 && __clang_minor__ <= 8
34 #define JSONCPP_TEMPLATE_DELETE
35 #endif
36 #endif
37 #if !defined(JSONCPP_TEMPLATE_DELETE)
38 #define JSONCPP_TEMPLATE_DELETE = delete
39 #endif
40 #endif
41
42 #ifndef JSONCPP_HAS_STRING_VIEW
43 #if __cplusplus >= 201703L
44 #define JSONCPP_HAS_STRING_VIEW 1
45 #endif
46 #endif
47
48 #include <array>
49 #include <exception>
50 #include <map>
51 #include <memory>
52 #include <string>
53 #include <vector>
54
55 // Forward declaration for testing.
56 struct ValueTest;
57
58 #ifdef JSONCPP_HAS_STRING_VIEW
59 #include <string_view>
60 #endif
61
62 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
63 // be used by...
64 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
65 #pragma warning(push)
66 #pragma warning(disable : 4251 4275)
67 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
68
69 #pragma pack(push)
70 #pragma pack()
71
72 /** \brief JSON (JavaScript Object Notation).
73 */
74 namespace Json {
75
76 #if JSON_USE_EXCEPTION
77 /** Base class for all exceptions we throw.
78 *
79 * We use nothing but these internally. Of course, STL can throw others.
80 */
81 class JSON_API Exception : public std::exception {
82 public:
83 Exception(String msg);
84 ~Exception() noexcept override;
85 char const* what() const noexcept override;
86
87 protected:
88 String msg_;
89 };
90
91 /** Exceptions which the user cannot easily avoid.
92 *
93 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
94 *
95 * \remark derived from Json::Exception
96 */
97 class JSON_API RuntimeError : public Exception {
98 public:
99 RuntimeError(String const& msg);
100 };
101
102 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
103 *
104 * These are precondition-violations (user bugs) and internal errors (our bugs).
105 *
106 * \remark derived from Json::Exception
107 */
108 class JSON_API LogicError : public Exception {
109 public:
110 LogicError(String const& msg);
111 };
112 #endif
113
114 /// used internally
115 JSONCPP_NORETURN void throwRuntimeError(String const& msg);
116 /// used internally
117 JSONCPP_NORETURN void throwLogicError(String const& msg);
118
119 /** \brief Type of the value held by a Value object.
120 */
121 enum ValueType {
122 nullValue = 0, ///< 'null' value
123 intValue, ///< signed integer value
124 uintValue, ///< unsigned integer value
125 realValue, ///< double value
126 stringValue, ///< UTF-8 string value
127 booleanValue, ///< bool value
128 arrayValue, ///< array value (ordered list)
129 objectValue ///< object value (collection of name/value pairs).
130 };
131
132 enum CommentPlacement {
133 commentBefore = 0, ///< a comment placed on the line before a value
134 commentAfterOnSameLine, ///< a comment just after a value on the same line
135 commentAfter, ///< a comment on the line after a value (only make sense for
136 /// root value)
137 numberOfCommentPlacement
138 };
139
140 /** \brief Type of precision for formatting of real values.
141 */
142 enum PrecisionType {
143 significantDigits = 0, ///< we set max number of significant digits in string
144 decimalPlaces ///< we set max number of digits after "." in string
145 };
146
147 /** \brief Lightweight wrapper to tag static string.
148 *
149 * Value constructor and objectValue member assignment takes advantage of the
150 * StaticString and avoid the cost of string duplication when storing the
151 * string or the member name.
152 *
153 * Example of usage:
154 * \code
155 * Json::Value aValue( StaticString("some text") );
156 * Json::Value object;
157 * static const StaticString code("code");
158 * object[code] = 1234;
159 * \endcode
160 */
161 class JSON_API StaticString {
162 public:
163 explicit StaticString(const char* czstring) : c_str_(czstring) {}
164
165 operator const char*() const { return c_str_; }
166
167 const char* c_str() const { return c_str_; }
168
169 private:
170 const char* c_str_;
171 };
172
173 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
174 *
175 * This class is a discriminated union wrapper that can represents a:
176 * - signed integer [range: Value::minInt - Value::maxInt]
177 * - unsigned integer (range: 0 - Value::maxUInt)
178 * - double
179 * - UTF-8 string
180 * - boolean
181 * - 'null'
182 * - an ordered list of Value
183 * - collection of name/value pairs (javascript object)
184 *
185 * The type of the held value is represented by a #ValueType and
186 * can be obtained using type().
187 *
188 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
189 * methods.
190 * Non-const methods will automatically create the a #nullValue element
191 * if it does not exist.
192 * The sequence of an #arrayValue will be automatically resized and initialized
193 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
194 *
195 * The get() methods can be used to obtain default value in the case the
196 * required element does not exist.
197 *
198 * It is possible to iterate over the list of member keys of an object using
199 * the getMemberNames() method.
200 *
201 * \note #Value string-length fit in size_t, but keys must be < 2^30.
202 * (The reason is an implementation detail.) A #CharReader will raise an
203 * exception if a bound is exceeded to avoid security holes in your app,
204 * but the Value API does *not* check bounds. That is the responsibility
205 * of the caller.
206 */
207 class JSON_API Value {
208 friend class ValueIteratorBase;
209 friend struct ::ValueTest;
210
211 public:
212 using Members = std::vector<String>;
213 using iterator = ValueIterator;
214 using const_iterator = ValueConstIterator;
215 using UInt = Json::UInt;
216 using Int = Json::Int;
217 #if defined(JSON_HAS_INT64)
218 using UInt64 = Json::UInt64;
219 using Int64 = Json::Int64;
220 #endif // defined(JSON_HAS_INT64)
221 using LargestInt = Json::LargestInt;
222 using LargestUInt = Json::LargestUInt;
223 using ArrayIndex = Json::ArrayIndex;
224
225 // Required for boost integration, e. g. BOOST_TEST
226 using value_type = std::string;
227
228 #if JSON_USE_NULLREF
229 // Binary compatibility kludges, do not use.
230 static const Value& null;
231 static const Value& nullRef;
232 #endif
233
234 // null and nullRef are deprecated, use this instead.
235 static Value const& nullSingleton();
236
237 /// Minimum signed integer value that can be stored in a Json::Value.
238 static constexpr LargestInt minLargestInt =
239 LargestInt(~(LargestUInt(-1) / 2));
240 /// Maximum signed integer value that can be stored in a Json::Value.
241 static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
242 /// Maximum unsigned integer value that can be stored in a Json::Value.
243 static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
244
245 /// Minimum signed int value that can be stored in a Json::Value.
246 static constexpr Int minInt = Int(~(UInt(-1) / 2));
247 /// Maximum signed int value that can be stored in a Json::Value.
248 static constexpr Int maxInt = Int(UInt(-1) / 2);
249 /// Maximum unsigned int value that can be stored in a Json::Value.
250 static constexpr UInt maxUInt = UInt(-1);
251
252 #if defined(JSON_HAS_INT64)
253 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
254 static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
255 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
256 static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
257 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
258 static constexpr UInt64 maxUInt64 = UInt64(-1);
259 #endif // defined(JSON_HAS_INT64)
260 /// Default precision for real value for string representation.
261 static constexpr UInt defaultRealPrecision = 17;
262 // The constant is hard-coded because some compiler have trouble
263 // converting Value::maxUInt64 to a double correctly (AIX/xlC).
264 // Assumes that UInt64 is a 64 bits integer.
265 static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
266 // Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
267 // when using gcc and clang backend compilers. CZString
268 // cannot be defined as private. See issue #486
269 #ifdef __NVCC__
270 public:
271 #else
272 private:
273 #endif
274 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
275 class JSON_API CZString {
276 public:
277 enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
278 CZString(ArrayIndex index);
279 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
280 CZString(CZString const& other);
281 CZString(CZString&& other) noexcept;
282 ~CZString();
283 CZString& operator=(const CZString& other);
284 CZString& operator=(CZString&& other) noexcept;
285
286 bool operator<(CZString const& other) const;
287 bool operator==(CZString const& other) const;
288 ArrayIndex index() const;
289 // const char* c_str() const; ///< \deprecated
290 char const* data() const;
291 unsigned length() const;
292 bool isStaticString() const;
293
294 private:
295 void swap(CZString& other);
296
297 struct StringStorage {
298 unsigned policy_ : 2;
299 unsigned length_ : 30; // 1GB max
300 };
301
302 char const* cstr_; // actually, a prefixed string, unless policy is noDup
303 union {
304 ArrayIndex index_;
305 StringStorage storage_;
306 };
307 };
308
309 public:
310 typedef std::map<CZString, Value> ObjectValues;
311 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
312
313 public:
314 /**
315 * \brief Create a default Value of the given type.
316 *
317 * This is a very useful constructor.
318 * To create an empty array, pass arrayValue.
319 * To create an empty object, pass objectValue.
320 * Another Value can then be set to this one by assignment.
321 * This is useful since clear() and resize() will not alter types.
322 *
323 * Examples:
324 * \code
325 * Json::Value null_value; // null
326 * Json::Value arr_value(Json::arrayValue); // []
327 * Json::Value obj_value(Json::objectValue); // {}
328 * \endcode
329 */
330 Value(ValueType type = nullValue);
331 Value(Int value);
332 Value(UInt value);
333 #if defined(JSON_HAS_INT64)
334 Value(Int64 value);
335 Value(UInt64 value);
336 #endif // if defined(JSON_HAS_INT64)
337 Value(double value);
338 Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
339 Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
340 /**
341 * \brief Constructs a value from a static string.
342 *
343 * Like other value string constructor but do not duplicate the string for
344 * internal storage. The given string must remain alive after the call to
345 * this constructor.
346 *
347 * \note This works only for null-terminated strings. (We cannot change the
348 * size of this class, so we have nowhere to store the length, which might be
349 * computed later for various operations.)
350 *
351 * Example of usage:
352 * \code
353 * static StaticString foo("some text");
354 * Json::Value aValue(foo);
355 * \endcode
356 */
357 Value(const StaticString& value);
358 Value(const String& value);
359 #ifdef JSONCPP_HAS_STRING_VIEW
360 Value(std::string_view value);
361 #endif
362 Value(bool value);
363 Value(std::nullptr_t ptr) = delete;
364 Value(const Value& other);
365 Value(Value&& other) noexcept;
366 ~Value();
367
368 /// \note Overwrite existing comments. To preserve comments, use
369 /// #swapPayload().
370 Value& operator=(const Value& other);
371 Value& operator=(Value&& other) noexcept;
372
373 /// Swap everything.
374 void swap(Value& other);
375 /// Swap values but leave comments and source offsets in place.
376 void swapPayload(Value& other);
377
378 /// copy everything.
379 void copy(const Value& other);
380 /// copy values but leave comments and source offsets in place.
381 void copyPayload(const Value& other);
382
383 ValueType type() const;
384
385 /// Compare payload only, not comments etc.
386 bool operator<(const Value& other) const;
387 bool operator<=(const Value& other) const;
388 bool operator>=(const Value& other) const;
389 bool operator>(const Value& other) const;
390 bool operator==(const Value& other) const;
391 bool operator!=(const Value& other) const;
392 int compare(const Value& other) const;
393
394 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
395 #if JSONCPP_USE_SECURE_MEMORY
396 unsigned getCStringLength() const; // Allows you to understand the length of
397 // the CString
398 #endif
399 String asString() const; ///< Embedded zeroes are possible.
400 /** Get raw char* of string-value.
401 * \return false if !string. (Seg-fault if str or end are NULL.)
402 */
403 bool getString(char const** begin, char const** end) const;
404 #ifdef JSONCPP_HAS_STRING_VIEW
405 /** Get string_view of string-value.
406 * \return false if !string. (Seg-fault if str is NULL.)
407 */
408 bool getString(std::string_view* str) const;
409 #endif
410 Int asInt() const;
411 UInt asUInt() const;
412 #if defined(JSON_HAS_INT64)
413 Int64 asInt64() const;
414 UInt64 asUInt64() const;
415 #endif // if defined(JSON_HAS_INT64)
416 LargestInt asLargestInt() const;
417 LargestUInt asLargestUInt() const;
418 float asFloat() const;
419 double asDouble() const;
420 bool asBool() const;
421
422 bool isNull() const;
423 bool isBool() const;
424 bool isInt() const;
425 bool isInt64() const;
426 bool isUInt() const;
427 bool isUInt64() const;
428 bool isIntegral() const;
429 bool isDouble() const;
430 bool isNumeric() const;
431 bool isString() const;
432 bool isArray() const;
433 bool isObject() const;
434
435 /// The `as<T>` and `is<T>` member function templates and specializations.
436 template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
437 template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
438
439 bool isConvertibleTo(ValueType other) const;
440
441 /// Number of values in array or object
442 ArrayIndex size() const;
443
444 /// \brief Return true if empty array, empty object, or null;
445 /// otherwise, false.
446 bool empty() const;
447
448 /// Return !isNull()
449 explicit operator bool() const;
450
451 /// Remove all object members and array elements.
452 /// \pre type() is arrayValue, objectValue, or nullValue
453 /// \post type() is unchanged
454 void clear();
455
456 /// Resize the array to newSize elements.
457 /// New elements are initialized to null.
458 /// May only be called on nullValue or arrayValue.
459 /// \pre type() is arrayValue or nullValue
460 /// \post type() is arrayValue
461 void resize(ArrayIndex newSize);
462
463 ///@{
464 /// Access an array element (zero based index). If the array contains less
465 /// than index element, then null value are inserted in the array so that
466 /// its size is index+1.
467 /// (You may need to say 'value[0u]' to get your compiler to distinguish
468 /// this from the operator[] which takes a string.)
469 Value& operator[](ArrayIndex index);
470 Value& operator[](int index);
471 ///@}
472
473 ///@{
474 /// Access an array element (zero based index).
475 /// (You may need to say 'value[0u]' to get your compiler to distinguish
476 /// this from the operator[] which takes a string.)
477 const Value& operator[](ArrayIndex index) const;
478 const Value& operator[](int index) const;
479 ///@}
480
481 /// If the array contains at least index+1 elements, returns the element
482 /// value, otherwise returns defaultValue.
483 Value get(ArrayIndex index, const Value& defaultValue) const;
484 /// Return true if index < size().
485 bool isValidIndex(ArrayIndex index) const;
486 /// \brief Append value to array at the end.
487 ///
488 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
489 Value& append(const Value& value);
490 Value& append(Value&& value);
491
492 /// \brief Insert value in array at specific index
493 bool insert(ArrayIndex index, const Value& newValue);
494 bool insert(ArrayIndex index, Value&& newValue);
495
496 #ifdef JSONCPP_HAS_STRING_VIEW
497 /// Access an object value by name, create a null member if it does not exist.
498 /// \param key may contain embedded nulls.
499 Value& operator[](std::string_view key);
500 /// Access an object value by name, returns null if there is no member with
501 /// that name.
502 /// \param key may contain embedded nulls.
503 const Value& operator[](std::string_view key) const;
504 #else
505 /// Access an object value by name, create a null member if it does not exist.
506 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
507 /// Exceeding that will cause an exception.
508 Value& operator[](const char* key);
509 /// Access an object value by name, returns null if there is no member with
510 /// that name.
511 const Value& operator[](const char* key) const;
512 /// Access an object value by name, create a null member if it does not exist.
513 /// \param key may contain embedded nulls.
514 Value& operator[](const String& key);
515 /// Access an object value by name, returns null if there is no member with
516 /// that name.
517 /// \param key may contain embedded nulls.
518 const Value& operator[](const String& key) const;
519 #endif
520 /** \brief Access an object value by name, create a null member if it does not
521 * exist.
522 *
523 * If the object has no entry for that name, then the member name used to
524 * store the new entry is not duplicated.
525 * Example of use:
526 * \code
527 * Json::Value object;
528 * static const StaticString code("code");
529 * object[code] = 1234;
530 * \endcode
531 */
532 Value& operator[](const StaticString& key);
533 #ifdef JSONCPP_HAS_STRING_VIEW
534 /// Return the member named key if it exist, defaultValue otherwise.
535 /// \note deep copy
536 Value get(std::string_view key, const Value& defaultValue) const;
537 #else
538 /// Return the member named key if it exist, defaultValue otherwise.
539 /// \note deep copy
540 Value get(const char* key, const Value& defaultValue) const;
541 /// Return the member named key if it exist, defaultValue otherwise.
542 /// \note deep copy
543 /// \param key may contain embedded nulls.
544 Value get(const String& key, const Value& defaultValue) const;
545 #endif
546 /// Return the member named key if it exist, defaultValue otherwise.
547 /// \note deep copy
548 /// \note key may contain embedded nulls.
549 Value get(const char* begin, const char* end,
550 const Value& defaultValue) const;
551 /// Most general and efficient version of isMember()const, get()const,
552 /// and operator[]const
553 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
554 Value const* find(char const* begin, char const* end) const;
555 /// Most general and efficient version of isMember()const, get()const,
556 /// and operator[]const
557 Value const* find(const String& key) const;
558
559 /// Calls find and only returns a valid pointer if the type is found
560 template <typename T, bool (T::*TMemFn)() const>
561 Value const* findValue(const String& key) const {
562 Value const* found = find(key);
563 if (!found || !(found->*TMemFn)())
564 return nullptr;
565 return found;
566 }
567
568 Value const* findNull(const String& key) const;
569 Value const* findBool(const String& key) const;
570 Value const* findInt(const String& key) const;
571 Value const* findInt64(const String& key) const;
572 Value const* findUInt(const String& key) const;
573 Value const* findUInt64(const String& key) const;
574 Value const* findIntegral(const String& key) const;
575 Value const* findDouble(const String& key) const;
576 Value const* findNumeric(const String& key) const;
577 Value const* findString(const String& key) const;
578 Value const* findArray(const String& key) const;
579 Value const* findObject(const String& key) const;
580
581 /// Most general and efficient version of object-mutators.
582 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
583 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
584 Value* demand(char const* begin, char const* end);
585 /// \brief Remove and return the named member.
586 ///
587 /// Do nothing if it did not exist.
588 /// \pre type() is objectValue or nullValue
589 /// \post type() is unchanged
590 #if JSONCPP_HAS_STRING_VIEW
591 void removeMember(std::string_view key);
592 #else
593 void removeMember(const char* key);
594 /// Same as removeMember(const char*)
595 /// \param key may contain embedded nulls.
596 void removeMember(const String& key);
597 #endif
598 /** \brief Remove the named map member.
599 *
600 * Update 'removed' iff removed.
601 * \param key may contain embedded nulls.
602 * \return true iff removed (no exceptions)
603 */
604 #if JSONCPP_HAS_STRING_VIEW
605 bool removeMember(std::string_view key, Value* removed);
606 #else
607 bool removeMember(String const& key, Value* removed);
608 /// Same as removeMember(const char* begin, const char* end, Value* removed),
609 /// but 'key' is null-terminated.
610 bool removeMember(const char* key, Value* removed);
611 #endif
612 /// Same as removeMember(String const& key, Value* removed)
613 bool removeMember(const char* begin, const char* end, Value* removed);
614 /** \brief Remove the indexed array element.
615 *
616 * O(n) expensive operations.
617 * Update 'removed' iff removed.
618 * \return true if removed (no exceptions)
619 */
620 bool removeIndex(ArrayIndex index, Value* removed);
621
622 #ifdef JSONCPP_HAS_STRING_VIEW
623 /// Return true if the object has a member named key.
624 /// \param key may contain embedded nulls.
625 bool isMember(std::string_view key) const;
626 #else
627 /// Return true if the object has a member named key.
628 /// \note 'key' must be null-terminated.
629 bool isMember(const char* key) const;
630 /// Return true if the object has a member named key.
631 /// \param key may contain embedded nulls.
632 bool isMember(const String& key) const;
633 #endif
634 /// Same as isMember(String const& key)const
635 bool isMember(const char* begin, const char* end) const;
636
637 /// \brief Return a list of the member names.
638 ///
639 /// If null, return an empty list.
640 /// \pre type() is objectValue or nullValue
641 /// \post if type() was nullValue, it remains nullValue
642 Members getMemberNames() const;
643
644 /// \deprecated Always pass len.
645 JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
646 void setComment(const char* comment, CommentPlacement placement) {
647 setComment(String(comment, strlen(comment)), placement);
648 }
649 /// Comments must be //... or /* ... */
650 void setComment(const char* comment, size_t len, CommentPlacement placement) {
651 setComment(String(comment, len), placement);
652 }
653 /// Comments must be //... or /* ... */
654 void setComment(String comment, CommentPlacement placement);
655 bool hasComment(CommentPlacement placement) const;
656 /// Include delimiters and embedded newlines.
657 String getComment(CommentPlacement placement) const;
658
659 String toStyledString() const;
660
661 const_iterator begin() const;
662 const_iterator end() const;
663
664 iterator begin();
665 iterator end();
666
667 /// \brief Returns a reference to the first element in the `Value`.
668 /// Requires that this value holds an array or json object, with at least one
669 /// element.
670 const Value& front() const;
671
672 /// \brief Returns a reference to the first element in the `Value`.
673 /// Requires that this value holds an array or json object, with at least one
674 /// element.
675 Value& front();
676
677 /// \brief Returns a reference to the last element in the `Value`.
678 /// Requires that value holds an array or json object, with at least one
679 /// element.
680 const Value& back() const;
681
682 /// \brief Returns a reference to the last element in the `Value`.
683 /// Requires that this value holds an array or json object, with at least one
684 /// element.
685 Value& back();
686
687 // Accessors for the [start, limit) range of bytes within the JSON text from
688 // which this value was parsed, if any.
689 void setOffsetStart(ptrdiff_t start);
690 void setOffsetLimit(ptrdiff_t limit);
691 ptrdiff_t getOffsetStart() const;
692 ptrdiff_t getOffsetLimit() const;
693
694 private:
695 void setType(ValueType v) {
696 bits_.value_type_ = static_cast<unsigned char>(v);
697 }
698 bool isAllocated() const { return bits_.allocated_; }
699 void setIsAllocated(bool v) { bits_.allocated_ = v; }
700
701 void initBasic(ValueType type, bool allocated = false);
702 void dupPayload(const Value& other);
703 void releasePayload();
704 void dupMeta(const Value& other);
705
706 Value& resolveReference(const char* key);
707 Value& resolveReference(const char* key, const char* end);
708
709 // struct MemberNamesTransform
710 //{
711 // typedef const char *result_type;
712 // const char *operator()( const CZString &name ) const
713 // {
714 // return name.c_str();
715 // }
716 //};
717
718 union ValueHolder {
719 LargestInt int_;
720 LargestUInt uint_;
721 double real_;
722 bool bool_;
723 char* string_; // if allocated_, ptr to { unsigned, char[] }.
724 ObjectValues* map_;
725 } value_;
726
727 struct {
728 // Really a ValueType, but types should agree for bitfield packing.
729 unsigned int value_type_ : 8;
730 // Unless allocated_, string_ must be null-terminated.
731 unsigned int allocated_ : 1;
732 } bits_;
733
734 class Comments {
735 public:
736 Comments() = default;
737 Comments(const Comments& that);
738 Comments(Comments&& that) noexcept;
739 Comments& operator=(const Comments& that);
740 Comments& operator=(Comments&& that) noexcept;
741 bool has(CommentPlacement slot) const;
742 String get(CommentPlacement slot) const;
743 void set(CommentPlacement slot, String comment);
744
745 private:
746 using Array = std::array<String, numberOfCommentPlacement>;
747 std::unique_ptr<Array> ptr_;
748 };
749 Comments comments_;
750
751 // [start, limit) byte offsets in the source JSON text from which this Value
752 // was extracted.
753 ptrdiff_t start_;
754 ptrdiff_t limit_;
755 };
756
757 template <> inline bool Value::as<bool>() const { return asBool(); }
758 template <> inline bool Value::is<bool>() const { return isBool(); }
759
760 template <> inline Int Value::as<Int>() const { return asInt(); }
761 template <> inline bool Value::is<Int>() const { return isInt(); }
762
763 template <> inline UInt Value::as<UInt>() const { return asUInt(); }
764 template <> inline bool Value::is<UInt>() const { return isUInt(); }
765
766 #if defined(JSON_HAS_INT64)
767 template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
768 template <> inline bool Value::is<Int64>() const { return isInt64(); }
769
770 template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
771 template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
772 #endif
773
774 template <> inline double Value::as<double>() const { return asDouble(); }
775 template <> inline bool Value::is<double>() const { return isDouble(); }
776
777 template <> inline String Value::as<String>() const { return asString(); }
778 template <> inline bool Value::is<String>() const { return isString(); }
779
780 /// These `as` specializations are type conversions, and do not have a
781 /// corresponding `is`.
782 template <> inline float Value::as<float>() const { return asFloat(); }
783 template <> inline const char* Value::as<const char*>() const {
784 return asCString();
785 }
786
787 /** \brief Experimental and untested: represents an element of the "path" to
788 * access a node.
789 */
790 class JSON_API PathArgument {
791 public:
792 friend class Path;
793
794 PathArgument();
795 PathArgument(ArrayIndex index);
796 PathArgument(const char* key);
797 PathArgument(String key);
798
799 private:
800 enum Kind { kindNone = 0, kindIndex, kindKey };
801 String key_;
802 ArrayIndex index_{};
803 Kind kind_{kindNone};
804 };
805
806 /** \brief Experimental and untested: represents a "path" to access a node.
807 *
808 * Syntax:
809 * - "." => root node
810 * - ".[n]" => elements at index 'n' of root node (an array value)
811 * - ".name" => member named 'name' of root node (an object value)
812 * - ".name1.name2.name3"
813 * - ".[0][1][2].name1[3]"
814 * - ".%" => member name is provided as parameter
815 * - ".[%]" => index is provided as parameter
816 */
817 class JSON_API Path {
818 public:
819 Path(const String& path, const PathArgument& a1 = PathArgument(),
820 const PathArgument& a2 = PathArgument(),
821 const PathArgument& a3 = PathArgument(),
822 const PathArgument& a4 = PathArgument(),
823 const PathArgument& a5 = PathArgument());
824
825 const Value& resolve(const Value& root) const;
826 Value resolve(const Value& root, const Value& defaultValue) const;
827 /// Creates the "path" to access the specified node and returns a reference on
828 /// the node.
829 Value& make(Value& root) const;
830
831 private:
832 using InArgs = std::vector<const PathArgument*>;
833 using Args = std::vector<PathArgument>;
834
835 void makePath(const String& path, const InArgs& in);
836 void addPathInArg(const String& path, const InArgs& in,
837 InArgs::const_iterator& itInArg, PathArgument::Kind kind);
838 static void invalidPath(const String& path, int location);
839
840 Args args_;
841 };
842
843 /** \brief base class for Value iterators.
844 *
845 */
846 class JSON_API ValueIteratorBase {
847 public:
848 using iterator_category = std::bidirectional_iterator_tag;
849 using size_t = unsigned int;
850 using difference_type = int;
851 using SelfType = ValueIteratorBase;
852
853 bool operator==(const SelfType& other) const { return isEqual(other); }
854
855 bool operator!=(const SelfType& other) const { return !isEqual(other); }
856
857 difference_type operator-(const SelfType& other) const {
858 return other.computeDistance(*this);
859 }
860
861 /// Return either the index or the member name of the referenced value as a
862 /// Value.
863 Value key() const;
864
865 /// Return the index of the referenced Value, or -1 if it is not an
866 /// arrayValue.
867 UInt index() const;
868
869 /// Return the member name of the referenced Value, or "" if it is not an
870 /// objectValue.
871 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
872 String name() const;
873
874 /// Return the member name of the referenced Value. "" if it is not an
875 /// objectValue.
876 /// \deprecated This cannot be used for UTF-8 strings, since there can be
877 /// embedded nulls.
878 JSONCPP_DEPRECATED("Use `key = name();` instead.")
879 char const* memberName() const;
880 /// Return the member name of the referenced Value, or NULL if it is not an
881 /// objectValue.
882 /// \note Better version than memberName(). Allows embedded nulls.
883 char const* memberName(char const** end) const;
884
885 protected:
886 /*! Internal utility functions to assist with implementing
887 * other iterator functions. The const and non-const versions
888 * of the "deref" protected methods expose the protected
889 * current_ member variable in a way that can often be
890 * optimized away by the compiler.
891 */
892 const Value& deref() const;
893 Value& deref();
894
895 void increment();
896
897 void decrement();
898
899 difference_type computeDistance(const SelfType& other) const;
900
901 bool isEqual(const SelfType& other) const;
902
903 void copy(const SelfType& other);
904
905 private:
906 Value::ObjectValues::iterator current_;
907 // Indicates that iterator is for a null value.
908 bool isNull_{true};
909
910 public:
911 // For some reason, BORLAND needs these at the end, rather
912 // than earlier. No idea why.
913 ValueIteratorBase();
914 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
915 };
916
917 /** \brief const iterator for object and array value.
918 *
919 */
920 class JSON_API ValueConstIterator : public ValueIteratorBase {
921 friend class Value;
922
923 public:
924 using value_type = const Value;
925 // typedef unsigned int size_t;
926 // typedef int difference_type;
927 using reference = const Value&;
928 using pointer = const Value*;
929 using SelfType = ValueConstIterator;
930
931 ValueConstIterator();
932 ValueConstIterator(ValueIterator const& other);
933
934 private:
935 /*! \internal Use by Value to create an iterator.
936 */
937 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
938
939 public:
940 SelfType& operator=(const ValueIteratorBase& other);
941
942 SelfType operator++(int) {
943 SelfType temp(*this);
944 ++*this;
945 return temp;
946 }
947
948 SelfType operator--(int) {
949 SelfType temp(*this);
950 --*this;
951 return temp;
952 }
953
954 SelfType& operator--() {
955 decrement();
956 return *this;
957 }
958
959 SelfType& operator++() {
960 increment();
961 return *this;
962 }
963
964 reference operator*() const { return deref(); }
965
966 pointer operator->() const { return &deref(); }
967 };
968
969 /** \brief Iterator for object and array value.
970 */
971 class JSON_API ValueIterator : public ValueIteratorBase {
972 friend class Value;
973
974 public:
975 using value_type = Value;
976 using size_t = unsigned int;
977 using difference_type = int;
978 using reference = Value&;
979 using pointer = Value*;
980 using SelfType = ValueIterator;
981
982 ValueIterator();
983 explicit ValueIterator(const ValueConstIterator& other);
984 ValueIterator(const ValueIterator& other);
985
986 private:
987 /*! \internal Use by Value to create an iterator.
988 */
989 explicit ValueIterator(const Value::ObjectValues::iterator& current);
990
991 public:
992 SelfType& operator=(const SelfType& other);
993
994 SelfType operator++(int) {
995 SelfType temp(*this);
996 ++*this;
997 return temp;
998 }
999
1000 SelfType operator--(int) {
1001 SelfType temp(*this);
1002 --*this;
1003 return temp;
1004 }
1005
1006 SelfType& operator--() {
1007 decrement();
1008 return *this;
1009 }
1010
1011 SelfType& operator++() {
1012 increment();
1013 return *this;
1014 }
1015
1016 /*! The return value of non-const iterators can be
1017 * changed, so the these functions are not const
1018 * because the returned references/pointers can be used
1019 * to change state of the base class.
1020 */
1021 reference operator*() const { return const_cast<reference>(deref()); }
1022 pointer operator->() const { return const_cast<pointer>(&deref()); }
1023 };
1024
1025 inline void swap(Value& a, Value& b) { a.swap(b); }
1026
1027 inline const Value& Value::front() const { return *begin(); }
1028
1029 inline Value& Value::front() { return *begin(); }
1030
1031 inline const Value& Value::back() const { return *(--end()); }
1032
1033 inline Value& Value::back() { return *(--end()); }
1034
1035 } // namespace Json
1036
1037 #pragma pack(pop)
1038
1039 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1040 #pragma warning(pop)
1041 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1042
1043 #endif // JSON_H_INCLUDED