Debian Codegraph @

include/json/value.h

raw ◀ ▶
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 inline Value(std::string_view value)
361 : Value(value.data(), value.data() + value.length()) {}
362 #endif
363 Value(bool value);
364 Value(std::nullptr_t ptr) = delete;
365 Value(const Value& other);
366 Value(Value&& other) noexcept;
367 ~Value();
368
369 /// \note Overwrite existing comments. To preserve comments, use
370 /// #swapPayload().
371 Value& operator=(const Value& other);
372 Value& operator=(Value&& other) noexcept;
373
374 /// Swap everything.
375 void swap(Value& other);
376 /// Swap values but leave comments and source offsets in place.
377 void swapPayload(Value& other);
378
379 /// copy everything.
380 void copy(const Value& other);
381 /// copy values but leave comments and source offsets in place.
382 void copyPayload(const Value& other);
383
384 ValueType type() const;
385
386 /// Compare payload only, not comments etc.
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 bool operator!=(const Value& other) const;
393 int compare(const Value& other) const;
394
395 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
396 #if JSONCPP_USE_SECURE_MEMORY
397 unsigned getCStringLength() const; // Allows you to understand the length of
398 // the CString
399 #endif
400 String asString() const; ///< Embedded zeroes are possible.
401 /** Get raw char* of string-value.
402 * \return false if !string. (Seg-fault if str or end are NULL.)
403 */
404 bool getString(char const** begin, char const** end) const;
405 #ifdef JSONCPP_HAS_STRING_VIEW
406 /** Get string_view of string-value.
407 * \return false if !string. (Seg-fault if str is NULL.)
408 */
•409 inline bool getString(std::string_view* str) const {
410 char const* begin;
411 char const* end;
412 if (!getString(&begin, &end))
413 return false;
414 *str = std::string_view(begin, static_cast<size_t>(end - begin));
415 return true;
416 }
417 #endif
418 Int asInt() const;
419 UInt asUInt() const;
420 #if defined(JSON_HAS_INT64)
421 Int64 asInt64() const;
422 UInt64 asUInt64() const;
423 #endif // if defined(JSON_HAS_INT64)
424 LargestInt asLargestInt() const;
425 LargestUInt asLargestUInt() const;
426 float asFloat() const;
427 double asDouble() const;
428 bool asBool() const;
429
430 bool isNull() const;
431 bool isBool() const;
432 bool isInt() const;
433 bool isInt64() const;
434 bool isUInt() const;
435 bool isUInt64() const;
436 bool isIntegral() const;
437 bool isDouble() const;
438 bool isNumeric() const;
439 bool isString() const;
440 bool isArray() const;
441 bool isObject() const;
442
443 /// The `as<T>` and `is<T>` member function templates and specializations.
444 template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
445 template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
446
447 bool isConvertibleTo(ValueType other) const;
448
449 /// Number of values in array or object
450 ArrayIndex size() const;
451
452 /// \brief Return true if empty array, empty object, or null;
453 /// otherwise, false.
454 bool empty() const;
455
456 /// Return !isNull()
457 explicit operator bool() const;
458
459 /// Remove all object members and array elements.
460 /// \pre type() is arrayValue, objectValue, or nullValue
461 /// \post type() is unchanged
462 void clear();
463
464 /// Resize the array to newSize elements.
465 /// New elements are initialized to null.
466 /// May only be called on nullValue or arrayValue.
467 /// \pre type() is arrayValue or nullValue
468 /// \post type() is arrayValue
469 void resize(ArrayIndex newSize);
470
471 ///@{
472 /// Access an array element (zero based index). If the array contains less
473 /// than index element, then null value are inserted in the array so that
474 /// its size is index+1.
475 /// (You may need to say 'value[0u]' to get your compiler to distinguish
476 /// this from the operator[] which takes a string.)
477 Value& operator[](ArrayIndex index);
478 Value& operator[](int index);
479 ///@}
480
481 ///@{
482 /// Access an array element (zero based index).
483 /// (You may need to say 'value[0u]' to get your compiler to distinguish
484 /// this from the operator[] which takes a string.)
485 const Value& operator[](ArrayIndex index) const;
486 const Value& operator[](int index) const;
487 ///@}
488
489 /// If the array contains at least index+1 elements, returns the element
490 /// value, otherwise returns defaultValue.
491 Value get(ArrayIndex index, const Value& defaultValue) const;
492 /// Return true if index < size().
493 bool isValidIndex(ArrayIndex index) const;
494 /// \brief Append value to array at the end.
495 ///
496 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
497 Value& append(const Value& value);
498 Value& append(Value&& value);
499
500 /// \brief Insert value in array at specific index
501 bool insert(ArrayIndex index, const Value& newValue);
502 bool insert(ArrayIndex index, Value&& newValue);
503
504 #ifdef JSONCPP_HAS_STRING_VIEW
505 /// Access an object value by name, create a null member if it does not exist.
506 /// \param key may contain embedded nulls.
•507 inline Value& operator[](std::string_view key) {
508 return resolveReference(key.data(), key.data() + key.length());
509 }
510 /// Access an object value by name, returns null if there is no member with
511 /// that name.
512 /// \param key may contain embedded nulls.
•513 inline const Value& operator[](std::string_view key) const {
514 Value const* found = find(key.data(), key.data() + key.length());
515 if (!found)
516 return nullSingleton();
517 return *found;
518 }
519 #endif
520 /// Access an object value by name, create a null member if it does not exist.
521 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
522 /// Exceeding that will cause an exception.
523 Value& operator[](const char* key);
524 /// Access an object value by name, returns null if there is no member with
525 /// that name.
526 const Value& operator[](const char* key) const;
527 /// Access an object value by name, create a null member if it does not exist.
528 /// \param key may contain embedded nulls.
529 Value& operator[](const String& key);
530 /// Access an object value by name, returns null if there is no member with
531 /// that name.
532 /// \param key may contain embedded nulls.
533 const Value& operator[](const String& key) const;
534 /** \brief Access an object value by name, create a null member if it does not
535 * exist.
536 *
537 * If the object has no entry for that name, then the member name used to
538 * store the new entry is not duplicated.
539 * Example of use:
540 * \code
541 * Json::Value object;
542 * static const StaticString code("code");
543 * object[code] = 1234;
544 * \endcode
545 */
546 Value& operator[](const StaticString& key);
547 #ifdef JSONCPP_HAS_STRING_VIEW
548 /// Return the member named key if it exist, defaultValue otherwise.
549 /// \note deep copy
•550 inline Value get(std::string_view key, const Value& defaultValue) const {
551 return get(key.data(), key.data() + key.length(), defaultValue);
552 }
553 #endif
554 /// Return the member named key if it exist, defaultValue otherwise.
555 /// \note deep copy
556 Value get(const char* key, const Value& defaultValue) const;
557 /// Return the member named key if it exist, defaultValue otherwise.
558 /// \note deep copy
559 /// \param key may contain embedded nulls.
560 Value get(const String& key, const Value& defaultValue) const;
561 /// Return the member named key if it exist, defaultValue otherwise.
562 /// \note deep copy
563 /// \note key may contain embedded nulls.
564 Value get(const char* begin, const char* end,
565 const Value& defaultValue) const;
566 /// Most general and efficient version of isMember()const, get()const,
567 /// and operator[]const
568 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
569 Value const* find(char const* begin, char const* end) const;
570 /// Most general and efficient version of isMember()const, get()const,
571 /// and operator[]const
572 Value const* find(const String& key) const;
573
574 /// Calls find and only returns a valid pointer if the type is found
575 template <typename T, bool (T::*TMemFn)() const>
576 Value const* findValue(const String& key) const {
577 Value const* found = find(key);
578 if (!found || !(found->*TMemFn)())
579 return nullptr;
580 return found;
581 }
582
583 Value const* findNull(const String& key) const;
584 Value const* findBool(const String& key) const;
585 Value const* findInt(const String& key) const;
586 Value const* findInt64(const String& key) const;
587 Value const* findUInt(const String& key) const;
588 Value const* findUInt64(const String& key) const;
589 Value const* findIntegral(const String& key) const;
590 Value const* findDouble(const String& key) const;
591 Value const* findNumeric(const String& key) const;
592 Value const* findString(const String& key) const;
593 Value const* findArray(const String& key) const;
594 Value const* findObject(const String& key) const;
595
596 /// Most general and efficient version of object-mutators.
597 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
598 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
599 Value* demand(char const* begin, char const* end);
600 /// \brief Remove and return the named member.
601 ///
602 /// Do nothing if it did not exist.
603 /// \pre type() is objectValue or nullValue
604 /// \post type() is unchanged
605 #if JSONCPP_HAS_STRING_VIEW
•606 inline void removeMember(std::string_view key) {
607 removeMember(key.data(), key.data() + key.length(), nullptr);
608 }
609 #endif
610 void removeMember(const char* key);
611 /// Same as removeMember(const char*)
612 /// \param key may contain embedded nulls.
613 void removeMember(const String& key);
614 /** \brief Remove the named map member.
615 *
616 * Update 'removed' iff removed.
617 * \param key may contain embedded nulls.
618 * \return true iff removed (no exceptions)
619 */
620 #if JSONCPP_HAS_STRING_VIEW
•621 inline bool removeMember(std::string_view key, Value* removed) {
622 return removeMember(key.data(), key.data() + key.length(), removed);
623 }
624 #endif
625 bool removeMember(String const& key, Value* removed);
626 /// Same as removeMember(const char* begin, const char* end, Value* removed),
627 /// but 'key' is null-terminated.
628 bool removeMember(const char* key, Value* removed);
629 /// Same as removeMember(String const& key, Value* removed)
630 bool removeMember(const char* begin, const char* end, Value* removed);
631 /** \brief Remove the indexed array element.
632 *
633 * O(n) expensive operations.
634 * Update 'removed' iff removed.
635 * \return true if removed (no exceptions)
636 */
637 bool removeIndex(ArrayIndex index, Value* removed);
638
639 #ifdef JSONCPP_HAS_STRING_VIEW
640 /// Return true if the object has a member named key.
641 /// \param key may contain embedded nulls.
•642 inline bool isMember(std::string_view key) const {
643 return isMember(key.data(), key.data() + key.length());
644 }
645 #endif
646 /// Return true if the object has a member named key.
647 /// \note 'key' must be null-terminated.
648 bool isMember(const char* key) const;
649 /// Return true if the object has a member named key.
650 /// \param key may contain embedded nulls.
651 bool isMember(const String& key) const;
652 /// Same as isMember(String const& key)const
653 bool isMember(const char* begin, const char* end) const;
654
655 /// \brief Return a list of the member names.
656 ///
657 /// If null, return an empty list.
658 /// \pre type() is objectValue or nullValue
659 /// \post if type() was nullValue, it remains nullValue
660 Members getMemberNames() const;
661
662 /// \deprecated Always pass len.
663 JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
664 void setComment(const char* comment, CommentPlacement placement) {
665 setComment(String(comment, strlen(comment)), placement);
666 }
667 /// Comments must be //... or /* ... */
668 void setComment(const char* comment, size_t len, CommentPlacement placement) {
669 setComment(String(comment, len), placement);
670 }
671 /// Comments must be //... or /* ... */
672 void setComment(String comment, CommentPlacement placement);
673 bool hasComment(CommentPlacement placement) const;
674 /// Include delimiters and embedded newlines.
675 String getComment(CommentPlacement placement) const;
676
677 String toStyledString() const;
678
679 const_iterator begin() const;
680 const_iterator end() const;
681
682 iterator begin();
683 iterator end();
684
685 /// \brief Returns a reference to the first element in the `Value`.
686 /// Requires that this value holds an array or json object, with at least one
687 /// element.
688 const Value& front() const;
689
690 /// \brief Returns a reference to the first element in the `Value`.
691 /// Requires that this value holds an array or json object, with at least one
692 /// element.
693 Value& front();
694
695 /// \brief Returns a reference to the last element in the `Value`.
696 /// Requires that value holds an array or json object, with at least one
697 /// element.
698 const Value& back() const;
699
700 /// \brief Returns a reference to the last element in the `Value`.
701 /// Requires that this value holds an array or json object, with at least one
702 /// element.
703 Value& back();
704
705 // Accessors for the [start, limit) range of bytes within the JSON text from
706 // which this value was parsed, if any.
707 void setOffsetStart(ptrdiff_t start);
708 void setOffsetLimit(ptrdiff_t limit);
709 ptrdiff_t getOffsetStart() const;
710 ptrdiff_t getOffsetLimit() const;
711
712 private:
713 void setType(ValueType v) {
714 bits_.value_type_ = static_cast<unsigned char>(v);
715 }
716 bool isAllocated() const { return bits_.allocated_; }
717 void setIsAllocated(bool v) { bits_.allocated_ = v; }
718
719 void initBasic(ValueType type, bool allocated = false);
720 void dupPayload(const Value& other);
721 void releasePayload();
722 void dupMeta(const Value& other);
723
724 Value& resolveReference(const char* key);
725 Value& resolveReference(const char* key, const char* end);
726
727 // struct MemberNamesTransform
728 //{
729 // typedef const char *result_type;
730 // const char *operator()( const CZString &name ) const
731 // {
732 // return name.c_str();
733 // }
734 //};
735
736 union ValueHolder {
737 LargestInt int_;
738 LargestUInt uint_;
739 double real_;
740 bool bool_;
741 char* string_; // if allocated_, ptr to { unsigned, char[] }.
742 ObjectValues* map_;
743 } value_;
744
745 struct {
746 // Really a ValueType, but types should agree for bitfield packing.
747 unsigned int value_type_ : 8;
748 // Unless allocated_, string_ must be null-terminated.
749 unsigned int allocated_ : 1;
750 } bits_;
751
752 class Comments {
753 public:
754 Comments() = default;
755 Comments(const Comments& that);
756 Comments(Comments&& that) noexcept;
757 Comments& operator=(const Comments& that);
758 Comments& operator=(Comments&& that) noexcept;
759 bool has(CommentPlacement slot) const;
760 String get(CommentPlacement slot) const;
761 void set(CommentPlacement slot, String comment);
762
763 private:
764 using Array = std::array<String, numberOfCommentPlacement>;
765 std::unique_ptr<Array> ptr_;
766 };
767 Comments comments_;
768
769 // [start, limit) byte offsets in the source JSON text from which this Value
770 // was extracted.
771 ptrdiff_t start_;
772 ptrdiff_t limit_;
773 };
774
775 template <> inline bool Value::as<bool>() const { return asBool(); }
776 template <> inline bool Value::is<bool>() const { return isBool(); }
777
778 template <> inline Int Value::as<Int>() const { return asInt(); }
779 template <> inline bool Value::is<Int>() const { return isInt(); }
780
781 template <> inline UInt Value::as<UInt>() const { return asUInt(); }
782 template <> inline bool Value::is<UInt>() const { return isUInt(); }
783
784 #if defined(JSON_HAS_INT64)
785 template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
786 template <> inline bool Value::is<Int64>() const { return isInt64(); }
787
788 template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
789 template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
790 #endif
791
792 template <> inline double Value::as<double>() const { return asDouble(); }
793 template <> inline bool Value::is<double>() const { return isDouble(); }
794
795 template <> inline String Value::as<String>() const { return asString(); }
796 template <> inline bool Value::is<String>() const { return isString(); }
797
798 /// These `as` specializations are type conversions, and do not have a
799 /// corresponding `is`.
800 template <> inline float Value::as<float>() const { return asFloat(); }
801 template <> inline const char* Value::as<const char*>() const {
802 return asCString();
803 }
804
805 /** \brief Experimental and untested: represents an element of the "path" to
806 * access a node.
807 */
808 class JSON_API PathArgument {
809 public:
810 friend class Path;
811
812 PathArgument();
813 PathArgument(ArrayIndex index);
814 PathArgument(const char* key);
815 PathArgument(String key);
816
817 private:
818 enum Kind { kindNone = 0, kindIndex, kindKey };
819 String key_;
820 ArrayIndex index_{};
821 Kind kind_{kindNone};
822 };
823
824 /** \brief Experimental and untested: represents a "path" to access a node.
825 *
826 * Syntax:
827 * - "." => root node
828 * - ".[n]" => elements at index 'n' of root node (an array value)
829 * - ".name" => member named 'name' of root node (an object value)
830 * - ".name1.name2.name3"
831 * - ".[0][1][2].name1[3]"
832 * - ".%" => member name is provided as parameter
833 * - ".[%]" => index is provided as parameter
834 */
835 class JSON_API Path {
836 public:
837 Path(const String& path, const PathArgument& a1 = PathArgument(),
838 const PathArgument& a2 = PathArgument(),
839 const PathArgument& a3 = PathArgument(),
840 const PathArgument& a4 = PathArgument(),
841 const PathArgument& a5 = PathArgument());
842
843 const Value& resolve(const Value& root) const;
844 Value resolve(const Value& root, const Value& defaultValue) const;
845 /// Creates the "path" to access the specified node and returns a reference on
846 /// the node.
847 Value& make(Value& root) const;
848
849 private:
850 using InArgs = std::vector<const PathArgument*>;
851 using Args = std::vector<PathArgument>;
852
853 void makePath(const String& path, const InArgs& in);
854 void addPathInArg(const String& path, const InArgs& in,
855 InArgs::const_iterator& itInArg, PathArgument::Kind kind);
856 static void invalidPath(const String& path, int location);
857
858 Args args_;
859 };
860
861 /** \brief base class for Value iterators.
862 *
863 */
864 class JSON_API ValueIteratorBase {
865 public:
866 using iterator_category = std::bidirectional_iterator_tag;
867 using size_t = unsigned int;
868 using difference_type = int;
869 using SelfType = ValueIteratorBase;
870
871 bool operator==(const SelfType& other) const { return isEqual(other); }
872
873 bool operator!=(const SelfType& other) const { return !isEqual(other); }
874
875 difference_type operator-(const SelfType& other) const {
876 return other.computeDistance(*this);
877 }
878
879 /// Return either the index or the member name of the referenced value as a
880 /// Value.
881 Value key() const;
882
883 /// Return the index of the referenced Value, or -1 if it is not an
884 /// arrayValue.
885 UInt index() const;
886
887 /// Return the member name of the referenced Value, or "" if it is not an
888 /// objectValue.
889 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
890 String name() const;
891
892 /// Return the member name of the referenced Value. "" if it is not an
893 /// objectValue.
894 /// \deprecated This cannot be used for UTF-8 strings, since there can be
895 /// embedded nulls.
896 JSONCPP_DEPRECATED("Use `key = name();` instead.")
897 char const* memberName() const;
898 /// Return the member name of the referenced Value, or NULL if it is not an
899 /// objectValue.
900 /// \note Better version than memberName(). Allows embedded nulls.
901 char const* memberName(char const** end) const;
902
903 protected:
904 /*! Internal utility functions to assist with implementing
905 * other iterator functions. The const and non-const versions
906 * of the "deref" protected methods expose the protected
907 * current_ member variable in a way that can often be
908 * optimized away by the compiler.
909 */
910 const Value& deref() const;
911 Value& deref();
912
913 void increment();
914
915 void decrement();
916
917 difference_type computeDistance(const SelfType& other) const;
918
919 bool isEqual(const SelfType& other) const;
920
921 void copy(const SelfType& other);
922
923 private:
924 Value::ObjectValues::iterator current_;
925 // Indicates that iterator is for a null value.
926 bool isNull_{true};
927
928 public:
929 // For some reason, BORLAND needs these at the end, rather
930 // than earlier. No idea why.
931 ValueIteratorBase();
932 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
933 };
934
935 /** \brief const iterator for object and array value.
936 *
937 */
938 class JSON_API ValueConstIterator : public ValueIteratorBase {
939 friend class Value;
940
941 public:
942 using value_type = const Value;
943 // typedef unsigned int size_t;
944 // typedef int difference_type;
945 using reference = const Value&;
946 using pointer = const Value*;
947 using SelfType = ValueConstIterator;
948
949 ValueConstIterator();
950 ValueConstIterator(ValueIterator const& other);
951
952 private:
953 /*! \internal Use by Value to create an iterator.
954 */
955 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
956
957 public:
958 SelfType& operator=(const ValueIteratorBase& other);
959
960 SelfType operator++(int) {
961 SelfType temp(*this);
962 ++*this;
963 return temp;
964 }
965
966 SelfType operator--(int) {
967 SelfType temp(*this);
968 --*this;
969 return temp;
970 }
971
972 SelfType& operator--() {
973 decrement();
974 return *this;
975 }
976
977 SelfType& operator++() {
978 increment();
979 return *this;
980 }
981
982 reference operator*() const { return deref(); }
983
984 pointer operator->() const { return &deref(); }
985 };
986
987 /** \brief Iterator for object and array value.
988 */
989 class JSON_API ValueIterator : public ValueIteratorBase {
990 friend class Value;
991
992 public:
993 using value_type = Value;
994 using size_t = unsigned int;
995 using difference_type = int;
996 using reference = Value&;
997 using pointer = Value*;
998 using SelfType = ValueIterator;
999
1000 ValueIterator();
1001 explicit ValueIterator(const ValueConstIterator& other);
1002 ValueIterator(const ValueIterator& other);
1003
1004 private:
1005 /*! \internal Use by Value to create an iterator.
1006 */
1007 explicit ValueIterator(const Value::ObjectValues::iterator& current);
1008
1009 public:
1010 SelfType& operator=(const SelfType& other);
1011
1012 SelfType operator++(int) {
1013 SelfType temp(*this);
1014 ++*this;
1015 return temp;
1016 }
1017
1018 SelfType operator--(int) {
1019 SelfType temp(*this);
1020 --*this;
1021 return temp;
1022 }
1023
1024 SelfType& operator--() {
1025 decrement();
1026 return *this;
1027 }
1028
1029 SelfType& operator++() {
1030 increment();
1031 return *this;
1032 }
1033
1034 /*! The return value of non-const iterators can be
1035 * changed, so the these functions are not const
1036 * because the returned references/pointers can be used
1037 * to change state of the base class.
1038 */
1039 reference operator*() const { return const_cast<reference>(deref()); }
1040 pointer operator->() const { return const_cast<pointer>(&deref()); }
1041 };
1042
1043 inline void swap(Value& a, Value& b) { a.swap(b); }
1044
1045 inline const Value& Value::front() const { return *begin(); }
1046
1047 inline Value& Value::front() { return *begin(); }
1048
1049 inline const Value& Value::back() const { return *(--end()); }
1050
1051 inline Value& Value::back() { return *(--end()); }
1052
1053 } // namespace Json
1054
1055 #pragma pack(pop)
1056
1057 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1058 #pragma warning(pop)
1059 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1060
1061 #endif // JSON_H_INCLUDED