JsonCpp project page Classes Namespace JsonCpp home page

value.h
Go to the documentation of 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#include <array>
43#include <exception>
44#include <map>
45#include <memory>
46#include <string>
47#include <vector>
48
49// Disable warning C4251: <data member>: <type> needs to have dll-interface to
50// be used by...
51#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
52#pragma warning(push)
53#pragma warning(disable : 4251 4275)
54#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
55
56#pragma pack(push)
57#pragma pack()
58
61namespace Json {
62
63#if JSON_USE_EXCEPTION
68class JSON_API Exception : public std::exception {
69public:
70 Exception(String msg);
71 ~Exception() noexcept override;
72 char const* what() const noexcept override;
73
74protected:
75 String msg_;
76};
77
85public:
86 RuntimeError(String const& msg);
87};
88
96public:
97 LogicError(String const& msg);
98};
99#endif
100
102JSONCPP_NORETURN void throwRuntimeError(String const& msg);
104JSONCPP_NORETURN void throwLogicError(String const& msg);
105
118
126
133
149public:
150 explicit StaticString(const char* czstring) : c_str_(czstring) {}
151
152 operator const char*() const { return c_str_; }
153
154 const char* c_str() const { return c_str_; }
155
156private:
157 const char* c_str_;
158};
159
195 friend class ValueIteratorBase;
196
197public:
198 using Members = std::vector<String>;
202 using Int = Json::Int;
203#if defined(JSON_HAS_INT64)
206#endif // defined(JSON_HAS_INT64)
210
211 // Required for boost integration, e. g. BOOST_TEST
212 using value_type = std::string;
213
214#if JSON_USE_NULLREF
215 // Binary compatibility kludges, do not use.
216 static const Value& null;
217 static const Value& nullRef;
218#endif
219
220 // null and nullRef are deprecated, use this instead.
221 static Value const& nullSingleton();
222
224 static constexpr LargestInt minLargestInt =
225 LargestInt(~(LargestUInt(-1) / 2));
227 static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
229 static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
230
232 static constexpr Int minInt = Int(~(UInt(-1) / 2));
234 static constexpr Int maxInt = Int(UInt(-1) / 2);
236 static constexpr UInt maxUInt = UInt(-1);
237
238#if defined(JSON_HAS_INT64)
240 static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
242 static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
244 static constexpr UInt64 maxUInt64 = UInt64(-1);
245#endif // defined(JSON_HAS_INT64)
247 static constexpr UInt defaultRealPrecision = 17;
248 // The constant is hard-coded because some compiler have trouble
249 // converting Value::maxUInt64 to a double correctly (AIX/xlC).
250 // Assumes that UInt64 is a 64 bits integer.
251 static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
252// Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
253// when using gcc and clang backend compilers. CZString
254// cannot be defined as private. See issue #486
255#ifdef __NVCC__
256public:
257#else
258private:
259#endif
260#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
261 class CZString {
262 public:
263 enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
264 CZString(ArrayIndex index);
265 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
266 CZString(CZString const& other);
267 CZString(CZString&& other) noexcept;
268 ~CZString();
269 CZString& operator=(const CZString& other);
270 CZString& operator=(CZString&& other) noexcept;
271
272 bool operator<(CZString const& other) const;
273 bool operator==(CZString const& other) const;
274 ArrayIndex index() const;
275 // const char* c_str() const; ///< \deprecated
276 char const* data() const;
277 unsigned length() const;
278 bool isStaticString() const;
279
280 private:
281 void swap(CZString& other);
282
283 struct StringStorage {
284 unsigned policy_ : 2;
285 unsigned length_ : 30; // 1GB max
286 };
287
288 char const* cstr_; // actually, a prefixed string, unless policy is noDup
289 union {
290 ArrayIndex index_;
291 StringStorage storage_;
292 };
293 };
294
295public:
296 typedef std::map<CZString, Value> ObjectValues;
297#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
298
299public:
316 Value(ValueType type = nullValue);
317 Value(Int value);
318 Value(UInt value);
319#if defined(JSON_HAS_INT64)
320 Value(Int64 value);
321 Value(UInt64 value);
322#endif // if defined(JSON_HAS_INT64)
323 Value(double value);
324 Value(const char* value);
325 Value(const char* begin, const char* end);
343 Value(const StaticString& value);
344 Value(const String& value);
345 Value(bool value);
346 Value(std::nullptr_t ptr) = delete;
347 Value(const Value& other);
348 Value(Value&& other) noexcept;
349 ~Value();
350
353 Value& operator=(const Value& other);
354 Value& operator=(Value&& other) noexcept;
355
357 void swap(Value& other);
359 void swapPayload(Value& other);
360
362 void copy(const Value& other);
364 void copyPayload(const Value& other);
365
366 ValueType type() const;
367
369 bool operator<(const Value& other) const;
370 bool operator<=(const Value& other) const;
371 bool operator>=(const Value& other) const;
372 bool operator>(const Value& other) const;
373 bool operator==(const Value& other) const;
374 bool operator!=(const Value& other) const;
375 int compare(const Value& other) const;
376
377 const char* asCString() const;
378#if JSONCPP_USING_SECURE_MEMORY
379 unsigned getCStringLength() const; // Allows you to understand the length of
380 // the CString
381#endif
382 String asString() const;
386 bool getString(char const** begin, char const** end) const;
387 Int asInt() const;
388 UInt asUInt() const;
389#if defined(JSON_HAS_INT64)
390 Int64 asInt64() const;
391 UInt64 asUInt64() const;
392#endif // if defined(JSON_HAS_INT64)
393 LargestInt asLargestInt() const;
394 LargestUInt asLargestUInt() const;
395 float asFloat() const;
396 double asDouble() const;
397 bool asBool() const;
398
399 bool isNull() const;
400 bool isBool() const;
401 bool isInt() const;
402 bool isInt64() const;
403 bool isUInt() const;
404 bool isUInt64() const;
405 bool isIntegral() const;
406 bool isDouble() const;
407 bool isNumeric() const;
408 bool isString() const;
409 bool isArray() const;
410 bool isObject() const;
411
413 template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
414 template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
415
416 bool isConvertibleTo(ValueType other) const;
417
419 ArrayIndex size() const;
420
423 bool empty() const;
424
426 explicit operator bool() const;
427
431 void clear();
432
438 void resize(ArrayIndex newSize);
439
446 Value& operator[](ArrayIndex index);
447 Value& operator[](int index);
449
454 const Value& operator[](ArrayIndex index) const;
455 const Value& operator[](int index) const;
457
460 Value get(ArrayIndex index, const Value& defaultValue) const;
462 bool isValidIndex(ArrayIndex index) const;
466 Value& append(const Value& value);
467 Value& append(Value&& value);
468
470 bool insert(ArrayIndex index, const Value& newValue);
471 bool insert(ArrayIndex index, Value&& newValue);
472
476 Value& operator[](const char* key);
479 const Value& operator[](const char* key) const;
482 Value& operator[](const String& key);
486 const Value& operator[](const String& key) const;
499 Value& operator[](const StaticString& key);
502 Value get(const char* key, const Value& defaultValue) const;
506 Value get(const char* begin, const char* end,
507 const Value& defaultValue) const;
511 Value get(const String& key, const Value& defaultValue) const;
515 Value const* find(char const* begin, char const* end) const;
518 Value const* find(const String& key) const;
522 Value* demand(char const* begin, char const* end);
528 void removeMember(const char* key);
531 void removeMember(const String& key);
534 bool removeMember(const char* key, Value* removed);
541 bool removeMember(String const& key, Value* removed);
543 bool removeMember(const char* begin, const char* end, Value* removed);
550 bool removeIndex(ArrayIndex index, Value* removed);
551
554 bool isMember(const char* key) const;
557 bool isMember(const String& key) const;
559 bool isMember(const char* begin, const char* end) const;
560
566 Members getMemberNames() const;
567
569 JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
570 void setComment(const char* comment, CommentPlacement placement) {
571 setComment(String(comment, strlen(comment)), placement);
572 }
574 void setComment(const char* comment, size_t len, CommentPlacement placement) {
575 setComment(String(comment, len), placement);
576 }
578 void setComment(String comment, CommentPlacement placement);
579 bool hasComment(CommentPlacement placement) const;
581 String getComment(CommentPlacement placement) const;
582
583 String toStyledString() const;
584
585 const_iterator begin() const;
586 const_iterator end() const;
587
588 iterator begin();
589 iterator end();
590
594 const Value& front() const;
595
599 Value& front();
600
604 const Value& back() const;
605
609 Value& back();
610
611 // Accessors for the [start, limit) range of bytes within the JSON text from
612 // which this value was parsed, if any.
613 void setOffsetStart(ptrdiff_t start);
614 void setOffsetLimit(ptrdiff_t limit);
615 ptrdiff_t getOffsetStart() const;
616 ptrdiff_t getOffsetLimit() const;
617
618private:
619 void setType(ValueType v) {
620 bits_.value_type_ = static_cast<unsigned char>(v);
621 }
622 bool isAllocated() const { return bits_.allocated_; }
623 void setIsAllocated(bool v) { bits_.allocated_ = v; }
624
625 void initBasic(ValueType type, bool allocated = false);
626 void dupPayload(const Value& other);
627 void releasePayload();
628 void dupMeta(const Value& other);
629
630 Value& resolveReference(const char* key);
631 Value& resolveReference(const char* key, const char* end);
632
633 // struct MemberNamesTransform
634 //{
635 // typedef const char *result_type;
636 // const char *operator()( const CZString &name ) const
637 // {
638 // return name.c_str();
639 // }
640 //};
641
642 union ValueHolder {
643 LargestInt int_;
644 LargestUInt uint_;
645 double real_;
646 bool bool_;
647 char* string_; // if allocated_, ptr to { unsigned, char[] }.
648 ObjectValues* map_;
649 } value_;
650
651 struct {
652 // Really a ValueType, but types should agree for bitfield packing.
653 unsigned int value_type_ : 8;
654 // Unless allocated_, string_ must be null-terminated.
655 unsigned int allocated_ : 1;
656 } bits_;
657
658 class Comments {
659 public:
660 Comments() = default;
661 Comments(const Comments& that);
662 Comments(Comments&& that) noexcept;
663 Comments& operator=(const Comments& that);
664 Comments& operator=(Comments&& that) noexcept;
665 bool has(CommentPlacement slot) const;
666 String get(CommentPlacement slot) const;
667 void set(CommentPlacement slot, String comment);
668
669 private:
670 using Array = std::array<String, numberOfCommentPlacement>;
671 std::unique_ptr<Array> ptr_;
672 };
673 Comments comments_;
674
675 // [start, limit) byte offsets in the source JSON text from which this Value
676 // was extracted.
677 ptrdiff_t start_;
678 ptrdiff_t limit_;
679};
680
681template <> inline bool Value::as<bool>() const { return asBool(); }
682template <> inline bool Value::is<bool>() const { return isBool(); }
683
684template <> inline Int Value::as<Int>() const { return asInt(); }
685template <> inline bool Value::is<Int>() const { return isInt(); }
686
687template <> inline UInt Value::as<UInt>() const { return asUInt(); }
688template <> inline bool Value::is<UInt>() const { return isUInt(); }
689
690#if defined(JSON_HAS_INT64)
691template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
692template <> inline bool Value::is<Int64>() const { return isInt64(); }
693
694template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
695template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
696#endif
697
698template <> inline double Value::as<double>() const { return asDouble(); }
699template <> inline bool Value::is<double>() const { return isDouble(); }
700
701template <> inline String Value::as<String>() const { return asString(); }
702template <> inline bool Value::is<String>() const { return isString(); }
703
706template <> inline float Value::as<float>() const { return asFloat(); }
707template <> inline const char* Value::as<const char*>() const {
708 return asCString();
709}
710
715public:
716 friend class Path;
717
720 PathArgument(const char* key);
721 PathArgument(String key);
722
723private:
724 enum Kind { kindNone = 0, kindIndex, kindKey };
725 String key_;
726 ArrayIndex index_{};
727 Kind kind_{kindNone};
728};
729
742public:
743 Path(const String& path, const PathArgument& a1 = PathArgument(),
744 const PathArgument& a2 = PathArgument(),
745 const PathArgument& a3 = PathArgument(),
746 const PathArgument& a4 = PathArgument(),
747 const PathArgument& a5 = PathArgument());
748
749 const Value& resolve(const Value& root) const;
750 Value resolve(const Value& root, const Value& defaultValue) const;
753 Value& make(Value& root) const;
754
755private:
756 using InArgs = std::vector<const PathArgument*>;
757 using Args = std::vector<PathArgument>;
758
759 void makePath(const String& path, const InArgs& in);
760 void addPathInArg(const String& path, const InArgs& in,
761 InArgs::const_iterator& itInArg, PathArgument::Kind kind);
762 static void invalidPath(const String& path, int location);
763
764 Args args_;
765};
766
771public:
772 using iterator_category = std::bidirectional_iterator_tag;
773 using size_t = unsigned int;
774 using difference_type = int;
776
777 bool operator==(const SelfType& other) const { return isEqual(other); }
778
779 bool operator!=(const SelfType& other) const { return !isEqual(other); }
780
781 difference_type operator-(const SelfType& other) const {
782 return other.computeDistance(*this);
783 }
784
787 Value key() const;
788
791 UInt index() const;
792
796 String name() const;
797
802 JSONCPP_DEPRECATED("Use `key = name();` instead.")
803 char const* memberName() const;
807 char const* memberName(char const** end) const;
808
809protected:
816 const Value& deref() const;
817 Value& deref();
818
819 void increment();
820
821 void decrement();
822
823 difference_type computeDistance(const SelfType& other) const;
824
825 bool isEqual(const SelfType& other) const;
826
827 void copy(const SelfType& other);
828
829private:
830 Value::ObjectValues::iterator current_;
831 // Indicates that iterator is for a null value.
832 bool isNull_{true};
833
834public:
835 // For some reason, BORLAND needs these at the end, rather
836 // than earlier. No idea why.
838 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
839};
840
845 friend class Value;
846
847public:
848 using value_type = const Value;
849 // typedef unsigned int size_t;
850 // typedef int difference_type;
851 using reference = const Value&;
852 using pointer = const Value*;
854
856 ValueConstIterator(ValueIterator const& other);
857
858private:
861 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
862
863public:
864 SelfType& operator=(const ValueIteratorBase& other);
865
867 SelfType temp(*this);
868 ++*this;
869 return temp;
870 }
871
873 SelfType temp(*this);
874 --*this;
875 return temp;
876 }
877
879 decrement();
880 return *this;
881 }
882
884 increment();
885 return *this;
886 }
887
888 reference operator*() const { return deref(); }
889
890 pointer operator->() const { return &deref(); }
891};
892
896 friend class Value;
897
898public:
900 using size_t = unsigned int;
901 using difference_type = int;
902 using reference = Value&;
903 using pointer = Value*;
905
907 explicit ValueIterator(const ValueConstIterator& other);
909
910private:
913 explicit ValueIterator(const Value::ObjectValues::iterator& current);
914
915public:
916 SelfType& operator=(const SelfType& other);
917
919 SelfType temp(*this);
920 ++*this;
921 return temp;
922 }
923
925 SelfType temp(*this);
926 --*this;
927 return temp;
928 }
929
931 decrement();
932 return *this;
933 }
934
936 increment();
937 return *this;
938 }
939
945 reference operator*() const { return const_cast<reference>(deref()); }
946 pointer operator->() const { return const_cast<pointer>(&deref()); }
947};
948
949inline void swap(Value& a, Value& b) { a.swap(b); }
950
951inline const Value& Value::front() const { return *begin(); }
952
953inline Value& Value::front() { return *begin(); }
954
955inline const Value& Value::back() const { return *(--end()); }
956
957inline Value& Value::back() { return *(--end()); }
958
959} // namespace Json
960
961#pragma pack(pop)
962
963#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
964#pragma warning(pop)
965#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
966
967#endif // JSON_H_INCLUDED
Base class for all exceptions we throw.
Definition value.h:68
~Exception() noexcept override
Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
Definition value.h:95
Experimental and untested: represents an element of the "path" to access a node.
Definition value.h:714
Experimental and untested: represents a "path" to access a node.
Definition value.h:741
Exceptions which the user cannot easily avoid.
Definition value.h:84
Lightweight wrapper to tag static string.
Definition value.h:148
const char * c_str() const
Definition value.h:154
StaticString(const char *czstring)
Definition value.h:150
const iterator for object and array value.
Definition value.h:844
SelfType & operator--()
Definition value.h:878
pointer operator->() const
Definition value.h:890
SelfType operator--(int)
Definition value.h:872
SelfType & operator++()
Definition value.h:883
SelfType operator++(int)
Definition value.h:866
reference operator*() const
Definition value.h:888
Represents a JSON value.
Definition value.h:194
Value(std::nullptr_t ptr)=delete
Json::ArrayIndex ArrayIndex
Definition value.h:209
Json::UInt UInt
Definition value.h:201
static const Value & null
Definition value.h:216
void setComment(const char *comment, size_t len, CommentPlacement placement)
Comments must be //... or /* ... *‍/.
Definition value.h:574
T as() const =delete
The as<T> and is<T> member function templates and specializations.
std::vector< String > Members
Definition value.h:198
Json::LargestInt LargestInt
Definition value.h:207
Json::LargestUInt LargestUInt
Definition value.h:208
Json::UInt64 UInt64
Definition value.h:204
void swap(Value &other)
Swap everything.
Json::Int Int
Definition value.h:202
static const Value & nullRef
Definition value.h:217
unsigned int value_type_
Definition value.h:653
Json::Int64 Int64
Definition value.h:205
unsigned int allocated_
Definition value.h:655
std::string value_type
Definition value.h:212
base class for Value iterators.
Definition value.h:770
bool operator==(const SelfType &other) const
Definition value.h:777
unsigned int size_t
Definition value.h:773
std::bidirectional_iterator_tag iterator_category
Definition value.h:772
difference_type operator-(const SelfType &other) const
Definition value.h:781
bool operator!=(const SelfType &other) const
Definition value.h:779
difference_type computeDistance(const SelfType &other) const
Iterator for object and array value.
Definition value.h:895
SelfType operator--(int)
Definition value.h:924
SelfType & operator--()
Definition value.h:930
reference operator*() const
Definition value.h:945
SelfType & operator++()
Definition value.h:935
unsigned int size_t
Definition value.h:900
ValueIterator(const ValueIterator &other)
pointer operator->() const
Definition value.h:946
SelfType operator++(int)
Definition value.h:918
#define JSON_API
If defined, indicates that the source file is amalgamated to prevent private header inclusion.
Definition config.h:50
#define JSONCPP_DEPRECATED(message)
Definition config.h:89
JSON (JavaScript Object Notation).
Definition allocator.h:15
unsigned int ArrayIndex
Definition forwards.h:32
std::basic_string< char, std::char_traits< char >, Allocator< char > > String
Definition config.h:132
CommentPlacement
Definition value.h:119
@ commentAfterOnSameLine
a comment just after a value on the same line
Definition value.h:121
@ commentBefore
a comment placed on the line before a value
Definition value.h:120
@ numberOfCommentPlacement
root value)
Definition value.h:124
@ commentAfter
a comment on the line after a value (only make sense for
Definition value.h:122
Int64 LargestInt
Definition config.h:123
ValueType
Type of the value held by a Value object.
Definition value.h:108
@ booleanValue
bool value
Definition value.h:114
@ nullValue
'null' value
Definition value.h:109
@ stringValue
UTF-8 string value.
Definition value.h:113
@ realValue
double value
Definition value.h:112
@ arrayValue
array value (ordered list)
Definition value.h:115
@ intValue
signed integer value
Definition value.h:110
@ objectValue
object value (collection of name/value pairs).
Definition value.h:116
@ uintValue
unsigned integer value
Definition value.h:111
bool operator==(const SecureAllocator< T > &, const SecureAllocator< U > &)
Definition allocator.h:78
bool operator!=(const SecureAllocator< T > &, const SecureAllocator< U > &)
Definition allocator.h:83
int Int
Definition config.h:108
UInt64 LargestUInt
Definition config.h:124
unsigned __int64 UInt64
Definition config.h:118
unsigned int UInt
Definition config.h:109
__int64 Int64
Definition config.h:117
PrecisionType
Type of precision for formatting of real values.
Definition value.h:129
@ decimalPlaces
we set max number of digits after "." in string
Definition value.h:131
@ significantDigits
we set max number of significant digits in string
Definition value.h:130
void swap(Value &a, Value &b)
Definition value.h:949
#define JSONCPP_TEMPLATE_DELETE
Definition value.h:38
#define JSONCPP_NORETURN
Definition value.h:18