pointer.h 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_POINTER_H_
  15. #define RAPIDJSON_POINTER_H_
  16. #include "document.h"
  17. #include "internal/itoa.h"
  18. #ifdef __clang__
  19. RAPIDJSON_DIAG_PUSH
  20. RAPIDJSON_DIAG_OFF(switch-enum)
  21. #elif defined(_MSC_VER)
  22. RAPIDJSON_DIAG_PUSH
  23. RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
  24. #endif
  25. RAPIDJSON_NAMESPACE_BEGIN
  26. static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token
  27. //! Error code of parsing.
  28. /*! \ingroup RAPIDJSON_ERRORS
  29. \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode
  30. */
  31. enum PointerParseErrorCode {
  32. kPointerParseErrorNone = 0, //!< The parse is successful
  33. kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a '/'
  34. kPointerParseErrorInvalidEscape, //!< Invalid escape
  35. kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI fragment
  36. kPointerParseErrorCharacterMustPercentEncode //!< A character must percent encoded in URI fragment
  37. };
  38. ///////////////////////////////////////////////////////////////////////////////
  39. // GenericPointer
  40. //! Represents a JSON Pointer. Use Pointer for UTF8 encoding and default allocator.
  41. /*!
  42. This class implements RFC 6901 "JavaScript Object Notation (JSON) Pointer"
  43. (https://tools.ietf.org/html/rfc6901).
  44. A JSON pointer is for identifying a specific value in a JSON document
  45. (GenericDocument). It can simplify coding of DOM tree manipulation, because it
  46. can access multiple-level depth of DOM tree with single API call.
  47. After it parses a string representation (e.g. "/foo/0" or URI fragment
  48. representation (e.g. "#/foo/0") into its internal representation (tokens),
  49. it can be used to resolve a specific value in multiple documents, or sub-tree
  50. of documents.
  51. Contrary to GenericValue, Pointer can be copy constructed and copy assigned.
  52. Apart from assignment, a Pointer cannot be modified after construction.
  53. Although Pointer is very convenient, please aware that constructing Pointer
  54. involves parsing and dynamic memory allocation. A special constructor with user-
  55. supplied tokens eliminates these.
  56. GenericPointer depends on GenericDocument and GenericValue.
  57. \tparam ValueType The value type of the DOM tree. E.g. GenericValue<UTF8<> >
  58. \tparam Allocator The allocator type for allocating memory for internal representation.
  59. \note GenericPointer uses same encoding of ValueType.
  60. However, Allocator of GenericPointer is independent of Allocator of Value.
  61. */
  62. template <typename ValueType, typename Allocator = CrtAllocator>
  63. class GenericPointer {
  64. public:
  65. typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value
  66. typedef typename ValueType::Ch Ch; //!< Character type from Value
  67. //! A token is the basic units of internal representation.
  68. /*!
  69. A JSON pointer string representation "/foo/123" is parsed to two tokens:
  70. "foo" and 123. 123 will be represented in both numeric form and string form.
  71. They are resolved according to the actual value type (object or array).
  72. For token that are not numbers, or the numeric value is out of bound
  73. (greater than limits of SizeType), they are only treated as string form
  74. (i.e. the token's index will be equal to kPointerInvalidIndex).
  75. This struct is public so that user can create a Pointer without parsing and
  76. allocation, using a special constructor.
  77. */
  78. struct Token {
  79. const Ch* name; //!< Name of the token. It has null character at the end but it can contain null character.
  80. SizeType length; //!< Length of the name.
  81. SizeType index; //!< A valid array index, if it is not equal to kPointerInvalidIndex.
  82. };
  83. //!@name Constructors and destructor.
  84. //@{
  85. //! Default constructor.
  86. GenericPointer(Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {}
  87. //! Constructor that parses a string or URI fragment representation.
  88. /*!
  89. \param source A null-terminated, string or URI fragment representation of JSON pointer.
  90. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
  91. */
  92. explicit GenericPointer(const Ch* source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
  93. Parse(source, internal::StrLen(source));
  94. }
  95. #if RAPIDJSON_HAS_STDSTRING
  96. //! Constructor that parses a string or URI fragment representation.
  97. /*!
  98. \param source A string or URI fragment representation of JSON pointer.
  99. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
  100. \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
  101. */
  102. explicit GenericPointer(const std::basic_string<Ch>& source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
  103. Parse(source.c_str(), source.size());
  104. }
  105. #endif
  106. //! Constructor that parses a string or URI fragment representation, with length of the source string.
  107. /*!
  108. \param source A string or URI fragment representation of JSON pointer.
  109. \param length Length of source.
  110. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
  111. \note Slightly faster than the overload without length.
  112. */
  113. GenericPointer(const Ch* source, size_t length, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
  114. Parse(source, length);
  115. }
  116. //! Constructor with user-supplied tokens.
  117. /*!
  118. This constructor let user supplies const array of tokens.
  119. This prevents the parsing process and eliminates allocation.
  120. This is preferred for memory constrained environments.
  121. \param tokens An constant array of tokens representing the JSON pointer.
  122. \param tokenCount Number of tokens.
  123. \b Example
  124. \code
  125. #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex }
  126. #define INDEX(i) { #i, sizeof(#i) - 1, i }
  127. static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) };
  128. static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0]));
  129. // Equivalent to static const Pointer p("/foo/123");
  130. #undef NAME
  131. #undef INDEX
  132. \endcode
  133. */
  134. GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast<Token*>(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {}
  135. //! Copy constructor.
  136. GenericPointer(const GenericPointer& rhs) : allocator_(rhs.allocator_), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
  137. *this = rhs;
  138. }
  139. //! Copy constructor.
  140. GenericPointer(const GenericPointer& rhs, Allocator* allocator) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
  141. *this = rhs;
  142. }
  143. //! Destructor.
  144. ~GenericPointer() {
  145. if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ is nullptr and tokens_ are not deallocated.
  146. Allocator::Free(tokens_);
  147. RAPIDJSON_DELETE(ownAllocator_);
  148. }
  149. //! Assignment operator.
  150. GenericPointer& operator=(const GenericPointer& rhs) {
  151. if (this != &rhs) {
  152. // Do not delete ownAllcator
  153. if (nameBuffer_)
  154. Allocator::Free(tokens_);
  155. tokenCount_ = rhs.tokenCount_;
  156. parseErrorOffset_ = rhs.parseErrorOffset_;
  157. parseErrorCode_ = rhs.parseErrorCode_;
  158. if (rhs.nameBuffer_)
  159. CopyFromRaw(rhs); // Normally parsed tokens.
  160. else {
  161. tokens_ = rhs.tokens_; // User supplied const tokens.
  162. nameBuffer_ = 0;
  163. }
  164. }
  165. return *this;
  166. }
  167. //@}
  168. //!@name Append token
  169. //@{
  170. //! Append a token and return a new Pointer
  171. /*!
  172. \param token Token to be appended.
  173. \param allocator Allocator for the newly return Pointer.
  174. \return A new Pointer with appended token.
  175. */
  176. GenericPointer Append(const Token& token, Allocator* allocator = 0) const {
  177. GenericPointer r;
  178. r.allocator_ = allocator;
  179. Ch *p = r.CopyFromRaw(*this, 1, token.length + 1);
  180. std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch));
  181. r.tokens_[tokenCount_].name = p;
  182. r.tokens_[tokenCount_].length = token.length;
  183. r.tokens_[tokenCount_].index = token.index;
  184. return r;
  185. }
  186. //! Append a name token with length, and return a new Pointer
  187. /*!
  188. \param name Name to be appended.
  189. \param length Length of name.
  190. \param allocator Allocator for the newly return Pointer.
  191. \return A new Pointer with appended token.
  192. */
  193. GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const {
  194. Token token = { name, length, kPointerInvalidIndex };
  195. return Append(token, allocator);
  196. }
  197. //! Append a name token without length, and return a new Pointer
  198. /*!
  199. \param name Name (const Ch*) to be appended.
  200. \param allocator Allocator for the newly return Pointer.
  201. \return A new Pointer with appended token.
  202. */
  203. template <typename T>
  204. RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer))
  205. Append(T* name, Allocator* allocator = 0) const {
  206. return Append(name, internal::StrLen(name), allocator);
  207. }
  208. #if RAPIDJSON_HAS_STDSTRING
  209. //! Append a name token, and return a new Pointer
  210. /*!
  211. \param name Name to be appended.
  212. \param allocator Allocator for the newly return Pointer.
  213. \return A new Pointer with appended token.
  214. */
  215. GenericPointer Append(const std::basic_string<Ch>& name, Allocator* allocator = 0) const {
  216. return Append(name.c_str(), static_cast<SizeType>(name.size()), allocator);
  217. }
  218. #endif
  219. //! Append a index token, and return a new Pointer
  220. /*!
  221. \param index Index to be appended.
  222. \param allocator Allocator for the newly return Pointer.
  223. \return A new Pointer with appended token.
  224. */
  225. GenericPointer Append(SizeType index, Allocator* allocator = 0) const {
  226. char buffer[21];
  227. char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer);
  228. SizeType length = static_cast<SizeType>(end - buffer);
  229. buffer[length] = '\0';
  230. if (sizeof(Ch) == 1) {
  231. Token token = { reinterpret_cast<Ch*>(buffer), length, index };
  232. return Append(token, allocator);
  233. }
  234. else {
  235. Ch name[21];
  236. for (size_t i = 0; i <= length; i++)
  237. name[i] = static_cast<Ch>(buffer[i]);
  238. Token token = { name, length, index };
  239. return Append(token, allocator);
  240. }
  241. }
  242. //! Append a token by value, and return a new Pointer
  243. /*!
  244. \param token token to be appended.
  245. \param allocator Allocator for the newly return Pointer.
  246. \return A new Pointer with appended token.
  247. */
  248. GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const {
  249. if (token.IsString())
  250. return Append(token.GetString(), token.GetStringLength(), allocator);
  251. else {
  252. RAPIDJSON_ASSERT(token.IsUint64());
  253. RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0));
  254. return Append(static_cast<SizeType>(token.GetUint64()), allocator);
  255. }
  256. }
  257. //!@name Handling Parse Error
  258. //@{
  259. //! Check whether this is a valid pointer.
  260. bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; }
  261. //! Get the parsing error offset in code unit.
  262. size_t GetParseErrorOffset() const { return parseErrorOffset_; }
  263. //! Get the parsing error code.
  264. PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; }
  265. //@}
  266. //! Get the allocator of this pointer.
  267. Allocator& GetAllocator() { return *allocator_; }
  268. //!@name Tokens
  269. //@{
  270. //! Get the token array (const version only).
  271. const Token* GetTokens() const { return tokens_; }
  272. //! Get the number of tokens.
  273. size_t GetTokenCount() const { return tokenCount_; }
  274. //@}
  275. //!@name Equality/inequality operators
  276. //@{
  277. //! Equality operator.
  278. /*!
  279. \note When any pointers are invalid, always returns false.
  280. */
  281. bool operator==(const GenericPointer& rhs) const {
  282. if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_)
  283. return false;
  284. for (size_t i = 0; i < tokenCount_; i++) {
  285. if (tokens_[i].index != rhs.tokens_[i].index ||
  286. tokens_[i].length != rhs.tokens_[i].length ||
  287. (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0))
  288. {
  289. return false;
  290. }
  291. }
  292. return true;
  293. }
  294. //! Inequality operator.
  295. /*!
  296. \note When any pointers are invalid, always returns true.
  297. */
  298. bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); }
  299. //@}
  300. //!@name Stringify
  301. //@{
  302. //! Stringify the pointer into string representation.
  303. /*!
  304. \tparam OutputStream Type of output stream.
  305. \param os The output stream.
  306. */
  307. template<typename OutputStream>
  308. bool Stringify(OutputStream& os) const {
  309. return Stringify<false, OutputStream>(os);
  310. }
  311. //! Stringify the pointer into URI fragment representation.
  312. /*!
  313. \tparam OutputStream Type of output stream.
  314. \param os The output stream.
  315. */
  316. template<typename OutputStream>
  317. bool StringifyUriFragment(OutputStream& os) const {
  318. return Stringify<true, OutputStream>(os);
  319. }
  320. //@}
  321. //!@name Create value
  322. //@{
  323. //! Create a value in a subtree.
  324. /*!
  325. If the value is not exist, it creates all parent values and a JSON Null value.
  326. So it always succeed and return the newly created or existing value.
  327. Remind that it may change types of parents according to tokens, so it
  328. potentially removes previously stored values. For example, if a document
  329. was an array, and "/foo" is used to create a value, then the document
  330. will be changed to an object, and all existing array elements are lost.
  331. \param root Root value of a DOM subtree to be resolved. It can be any value other than document root.
  332. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  333. \param alreadyExist If non-null, it stores whether the resolved value is already exist.
  334. \return The resolved newly created (a JSON Null value), or already exists value.
  335. */
  336. ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const {
  337. RAPIDJSON_ASSERT(IsValid());
  338. ValueType* v = &root;
  339. bool exist = true;
  340. for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  341. if (v->IsArray() && t->name[0] == '-' && t->length == 1) {
  342. v->PushBack(ValueType().Move(), allocator);
  343. v = &((*v)[v->Size() - 1]);
  344. exist = false;
  345. }
  346. else {
  347. if (t->index == kPointerInvalidIndex) { // must be object name
  348. if (!v->IsObject())
  349. v->SetObject(); // Change to Object
  350. }
  351. else { // object name or array index
  352. if (!v->IsArray() && !v->IsObject())
  353. v->SetArray(); // Change to Array
  354. }
  355. if (v->IsArray()) {
  356. if (t->index >= v->Size()) {
  357. v->Reserve(t->index + 1, allocator);
  358. while (t->index >= v->Size())
  359. v->PushBack(ValueType().Move(), allocator);
  360. exist = false;
  361. }
  362. v = &((*v)[t->index]);
  363. }
  364. else {
  365. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  366. if (m == v->MemberEnd()) {
  367. v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator);
  368. v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end
  369. exist = false;
  370. }
  371. else
  372. v = &m->value;
  373. }
  374. }
  375. }
  376. if (alreadyExist)
  377. *alreadyExist = exist;
  378. return *v;
  379. }
  380. //! Creates a value in a document.
  381. /*!
  382. \param document A document to be resolved.
  383. \param alreadyExist If non-null, it stores whether the resolved value is already exist.
  384. \return The resolved newly created, or already exists value.
  385. */
  386. template <typename stackAllocator>
  387. ValueType& Create(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, bool* alreadyExist = 0) const {
  388. return Create(document, document.GetAllocator(), alreadyExist);
  389. }
  390. //@}
  391. //!@name Query value
  392. //@{
  393. //! Query a value in a subtree.
  394. /*!
  395. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  396. \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token.
  397. \return Pointer to the value if it can be resolved. Otherwise null.
  398. \note
  399. There are only 3 situations when a value cannot be resolved:
  400. 1. A value in the path is not an array nor object.
  401. 2. An object value does not contain the token.
  402. 3. A token is out of range of an array value.
  403. Use unresolvedTokenIndex to retrieve the token index.
  404. */
  405. ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const {
  406. RAPIDJSON_ASSERT(IsValid());
  407. ValueType* v = &root;
  408. for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  409. switch (v->GetType()) {
  410. case kObjectType:
  411. {
  412. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  413. if (m == v->MemberEnd())
  414. break;
  415. v = &m->value;
  416. }
  417. continue;
  418. case kArrayType:
  419. if (t->index == kPointerInvalidIndex || t->index >= v->Size())
  420. break;
  421. v = &((*v)[t->index]);
  422. continue;
  423. default:
  424. break;
  425. }
  426. // Error: unresolved token
  427. if (unresolvedTokenIndex)
  428. *unresolvedTokenIndex = static_cast<size_t>(t - tokens_);
  429. return 0;
  430. }
  431. return v;
  432. }
  433. //! Query a const value in a const subtree.
  434. /*!
  435. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  436. \return Pointer to the value if it can be resolved. Otherwise null.
  437. */
  438. const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const {
  439. return Get(const_cast<ValueType&>(root), unresolvedTokenIndex);
  440. }
  441. //@}
  442. //!@name Query a value with default
  443. //@{
  444. //! Query a value in a subtree with default value.
  445. /*!
  446. Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value.
  447. So that this function always succeed.
  448. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  449. \param defaultValue Default value to be cloned if the value was not exists.
  450. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  451. \see Create()
  452. */
  453. ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const {
  454. bool alreadyExist;
  455. ValueType& v = Create(root, allocator, &alreadyExist);
  456. return alreadyExist ? v : v.CopyFrom(defaultValue, allocator);
  457. }
  458. //! Query a value in a subtree with default null-terminated string.
  459. ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const {
  460. bool alreadyExist;
  461. ValueType& v = Create(root, allocator, &alreadyExist);
  462. return alreadyExist ? v : v.SetString(defaultValue, allocator);
  463. }
  464. #if RAPIDJSON_HAS_STDSTRING
  465. //! Query a value in a subtree with default std::basic_string.
  466. ValueType& GetWithDefault(ValueType& root, const std::basic_string<Ch>& defaultValue, typename ValueType::AllocatorType& allocator) const {
  467. bool alreadyExist;
  468. ValueType& v = Create(root, allocator, &alreadyExist);
  469. return alreadyExist ? v : v.SetString(defaultValue, allocator);
  470. }
  471. #endif
  472. //! Query a value in a subtree with default primitive value.
  473. /*!
  474. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  475. */
  476. template <typename T>
  477. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  478. GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const {
  479. return GetWithDefault(root, ValueType(defaultValue).Move(), allocator);
  480. }
  481. //! Query a value in a document with default value.
  482. template <typename stackAllocator>
  483. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& defaultValue) const {
  484. return GetWithDefault(document, defaultValue, document.GetAllocator());
  485. }
  486. //! Query a value in a document with default null-terminated string.
  487. template <typename stackAllocator>
  488. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* defaultValue) const {
  489. return GetWithDefault(document, defaultValue, document.GetAllocator());
  490. }
  491. #if RAPIDJSON_HAS_STDSTRING
  492. //! Query a value in a document with default std::basic_string.
  493. template <typename stackAllocator>
  494. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& defaultValue) const {
  495. return GetWithDefault(document, defaultValue, document.GetAllocator());
  496. }
  497. #endif
  498. //! Query a value in a document with default primitive value.
  499. /*!
  500. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  501. */
  502. template <typename T, typename stackAllocator>
  503. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  504. GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T defaultValue) const {
  505. return GetWithDefault(document, defaultValue, document.GetAllocator());
  506. }
  507. //@}
  508. //!@name Set a value
  509. //@{
  510. //! Set a value in a subtree, with move semantics.
  511. /*!
  512. It creates all parents if they are not exist or types are different to the tokens.
  513. So this function always succeeds but potentially remove existing values.
  514. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  515. \param value Value to be set.
  516. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  517. \see Create()
  518. */
  519. ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
  520. return Create(root, allocator) = value;
  521. }
  522. //! Set a value in a subtree, with copy semantics.
  523. ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const {
  524. return Create(root, allocator).CopyFrom(value, allocator);
  525. }
  526. //! Set a null-terminated string in a subtree.
  527. ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const {
  528. return Create(root, allocator) = ValueType(value, allocator).Move();
  529. }
  530. #if RAPIDJSON_HAS_STDSTRING
  531. //! Set a std::basic_string in a subtree.
  532. ValueType& Set(ValueType& root, const std::basic_string<Ch>& value, typename ValueType::AllocatorType& allocator) const {
  533. return Create(root, allocator) = ValueType(value, allocator).Move();
  534. }
  535. #endif
  536. //! Set a primitive value in a subtree.
  537. /*!
  538. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  539. */
  540. template <typename T>
  541. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  542. Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const {
  543. return Create(root, allocator) = ValueType(value).Move();
  544. }
  545. //! Set a value in a document, with move semantics.
  546. template <typename stackAllocator>
  547. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
  548. return Create(document) = value;
  549. }
  550. //! Set a value in a document, with copy semantics.
  551. template <typename stackAllocator>
  552. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& value) const {
  553. return Create(document).CopyFrom(value, document.GetAllocator());
  554. }
  555. //! Set a null-terminated string in a document.
  556. template <typename stackAllocator>
  557. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* value) const {
  558. return Create(document) = ValueType(value, document.GetAllocator()).Move();
  559. }
  560. #if RAPIDJSON_HAS_STDSTRING
  561. //! Sets a std::basic_string in a document.
  562. template <typename stackAllocator>
  563. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& value) const {
  564. return Create(document) = ValueType(value, document.GetAllocator()).Move();
  565. }
  566. #endif
  567. //! Set a primitive value in a document.
  568. /*!
  569. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  570. */
  571. template <typename T, typename stackAllocator>
  572. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  573. Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T value) const {
  574. return Create(document) = value;
  575. }
  576. //@}
  577. //!@name Swap a value
  578. //@{
  579. //! Swap a value with a value in a subtree.
  580. /*!
  581. It creates all parents if they are not exist or types are different to the tokens.
  582. So this function always succeeds but potentially remove existing values.
  583. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  584. \param value Value to be swapped.
  585. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  586. \see Create()
  587. */
  588. ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
  589. return Create(root, allocator).Swap(value);
  590. }
  591. //! Swap a value with a value in a document.
  592. template <typename stackAllocator>
  593. ValueType& Swap(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
  594. return Create(document).Swap(value);
  595. }
  596. //@}
  597. //! Erase a value in a subtree.
  598. /*!
  599. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  600. \return Whether the resolved value is found and erased.
  601. \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false.
  602. */
  603. bool Erase(ValueType& root) const {
  604. RAPIDJSON_ASSERT(IsValid());
  605. if (tokenCount_ == 0) // Cannot erase the root
  606. return false;
  607. ValueType* v = &root;
  608. const Token* last = tokens_ + (tokenCount_ - 1);
  609. for (const Token *t = tokens_; t != last; ++t) {
  610. switch (v->GetType()) {
  611. case kObjectType:
  612. {
  613. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  614. if (m == v->MemberEnd())
  615. return false;
  616. v = &m->value;
  617. }
  618. break;
  619. case kArrayType:
  620. if (t->index == kPointerInvalidIndex || t->index >= v->Size())
  621. return false;
  622. v = &((*v)[t->index]);
  623. break;
  624. default:
  625. return false;
  626. }
  627. }
  628. switch (v->GetType()) {
  629. case kObjectType:
  630. return v->EraseMember(GenericStringRef<Ch>(last->name, last->length));
  631. case kArrayType:
  632. if (last->index == kPointerInvalidIndex || last->index >= v->Size())
  633. return false;
  634. v->Erase(v->Begin() + last->index);
  635. return true;
  636. default:
  637. return false;
  638. }
  639. }
  640. private:
  641. //! Clone the content from rhs to this.
  642. /*!
  643. \param rhs Source pointer.
  644. \param extraToken Extra tokens to be allocated.
  645. \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated.
  646. \return Start of non-occupied name buffer, for storing extra names.
  647. */
  648. Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) {
  649. if (!allocator_) // allocator is independently owned.
  650. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
  651. size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens
  652. for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t)
  653. nameBufferSize += t->length;
  654. tokenCount_ = rhs.tokenCount_ + extraToken;
  655. tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch)));
  656. nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
  657. if (rhs.tokenCount_ > 0) {
  658. std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token));
  659. }
  660. if (nameBufferSize > 0) {
  661. std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch));
  662. }
  663. // Adjust pointers to name buffer
  664. std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_;
  665. for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t)
  666. t->name += diff;
  667. return nameBuffer_ + nameBufferSize;
  668. }
  669. //! Check whether a character should be percent-encoded.
  670. /*!
  671. According to RFC 3986 2.3 Unreserved Characters.
  672. \param c The character (code unit) to be tested.
  673. */
  674. bool NeedPercentEncode(Ch c) const {
  675. return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~');
  676. }
  677. //! Parse a JSON String or its URI fragment representation into tokens.
  678. #ifndef __clang__ // -Wdocumentation
  679. /*!
  680. \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated.
  681. \param length Length of the source string.
  682. \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped.
  683. */
  684. #endif
  685. void Parse(const Ch* source, size_t length) {
  686. RAPIDJSON_ASSERT(source != NULL);
  687. RAPIDJSON_ASSERT(nameBuffer_ == 0);
  688. RAPIDJSON_ASSERT(tokens_ == 0);
  689. // Create own allocator if user did not supply.
  690. if (!allocator_)
  691. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
  692. // Count number of '/' as tokenCount
  693. tokenCount_ = 0;
  694. for (const Ch* s = source; s != source + length; s++)
  695. if (*s == '/')
  696. tokenCount_++;
  697. Token* token = tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch)));
  698. Ch* name = nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
  699. size_t i = 0;
  700. // Detect if it is a URI fragment
  701. bool uriFragment = false;
  702. if (source[i] == '#') {
  703. uriFragment = true;
  704. i++;
  705. }
  706. if (i != length && source[i] != '/') {
  707. parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus;
  708. goto error;
  709. }
  710. while (i < length) {
  711. RAPIDJSON_ASSERT(source[i] == '/');
  712. i++; // consumes '/'
  713. token->name = name;
  714. bool isNumber = true;
  715. while (i < length && source[i] != '/') {
  716. Ch c = source[i];
  717. if (uriFragment) {
  718. // Decoding percent-encoding for URI fragment
  719. if (c == '%') {
  720. PercentDecodeStream is(&source[i], source + length);
  721. GenericInsituStringStream<EncodingType> os(name);
  722. Ch* begin = os.PutBegin();
  723. if (!Transcoder<UTF8<>, EncodingType>().Validate(is, os) || !is.IsValid()) {
  724. parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding;
  725. goto error;
  726. }
  727. size_t len = os.PutEnd(begin);
  728. i += is.Tell() - 1;
  729. if (len == 1)
  730. c = *name;
  731. else {
  732. name += len;
  733. isNumber = false;
  734. i++;
  735. continue;
  736. }
  737. }
  738. else if (NeedPercentEncode(c)) {
  739. parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode;
  740. goto error;
  741. }
  742. }
  743. i++;
  744. // Escaping "~0" -> '~', "~1" -> '/'
  745. if (c == '~') {
  746. if (i < length) {
  747. c = source[i];
  748. if (c == '0') c = '~';
  749. else if (c == '1') c = '/';
  750. else {
  751. parseErrorCode_ = kPointerParseErrorInvalidEscape;
  752. goto error;
  753. }
  754. i++;
  755. }
  756. else {
  757. parseErrorCode_ = kPointerParseErrorInvalidEscape;
  758. goto error;
  759. }
  760. }
  761. // First check for index: all of characters are digit
  762. if (c < '0' || c > '9')
  763. isNumber = false;
  764. *name++ = c;
  765. }
  766. token->length = static_cast<SizeType>(name - token->name);
  767. if (token->length == 0)
  768. isNumber = false;
  769. *name++ = '\0'; // Null terminator
  770. // Second check for index: more than one digit cannot have leading zero
  771. if (isNumber && token->length > 1 && token->name[0] == '0')
  772. isNumber = false;
  773. // String to SizeType conversion
  774. SizeType n = 0;
  775. if (isNumber) {
  776. for (size_t j = 0; j < token->length; j++) {
  777. SizeType m = n * 10 + static_cast<SizeType>(token->name[j] - '0');
  778. if (m < n) { // overflow detection
  779. isNumber = false;
  780. break;
  781. }
  782. n = m;
  783. }
  784. }
  785. token->index = isNumber ? n : kPointerInvalidIndex;
  786. token++;
  787. }
  788. RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer
  789. parseErrorCode_ = kPointerParseErrorNone;
  790. return;
  791. error:
  792. Allocator::Free(tokens_);
  793. nameBuffer_ = 0;
  794. tokens_ = 0;
  795. tokenCount_ = 0;
  796. parseErrorOffset_ = i;
  797. return;
  798. }
  799. //! Stringify to string or URI fragment representation.
  800. /*!
  801. \tparam uriFragment True for stringifying to URI fragment representation. False for string representation.
  802. \tparam OutputStream type of output stream.
  803. \param os The output stream.
  804. */
  805. template<bool uriFragment, typename OutputStream>
  806. bool Stringify(OutputStream& os) const {
  807. RAPIDJSON_ASSERT(IsValid());
  808. if (uriFragment)
  809. os.Put('#');
  810. for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  811. os.Put('/');
  812. for (size_t j = 0; j < t->length; j++) {
  813. Ch c = t->name[j];
  814. if (c == '~') {
  815. os.Put('~');
  816. os.Put('0');
  817. }
  818. else if (c == '/') {
  819. os.Put('~');
  820. os.Put('1');
  821. }
  822. else if (uriFragment && NeedPercentEncode(c)) {
  823. // Transcode to UTF8 sequence
  824. GenericStringStream<typename ValueType::EncodingType> source(&t->name[j]);
  825. PercentEncodeStream<OutputStream> target(os);
  826. if (!Transcoder<EncodingType, UTF8<> >().Validate(source, target))
  827. return false;
  828. j += source.Tell() - 1;
  829. }
  830. else
  831. os.Put(c);
  832. }
  833. }
  834. return true;
  835. }
  836. //! A helper stream for decoding a percent-encoded sequence into code unit.
  837. /*!
  838. This stream decodes %XY triplet into code unit (0-255).
  839. If it encounters invalid characters, it sets output code unit as 0 and
  840. mark invalid, and to be checked by IsValid().
  841. */
  842. class PercentDecodeStream {
  843. public:
  844. typedef typename ValueType::Ch Ch;
  845. //! Constructor
  846. /*!
  847. \param source Start of the stream
  848. \param end Past-the-end of the stream.
  849. */
  850. PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {}
  851. Ch Take() {
  852. if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet
  853. valid_ = false;
  854. return 0;
  855. }
  856. src_++;
  857. Ch c = 0;
  858. for (int j = 0; j < 2; j++) {
  859. c = static_cast<Ch>(c << 4);
  860. Ch h = *src_;
  861. if (h >= '0' && h <= '9') c = static_cast<Ch>(c + h - '0');
  862. else if (h >= 'A' && h <= 'F') c = static_cast<Ch>(c + h - 'A' + 10);
  863. else if (h >= 'a' && h <= 'f') c = static_cast<Ch>(c + h - 'a' + 10);
  864. else {
  865. valid_ = false;
  866. return 0;
  867. }
  868. src_++;
  869. }
  870. return c;
  871. }
  872. size_t Tell() const { return static_cast<size_t>(src_ - head_); }
  873. bool IsValid() const { return valid_; }
  874. private:
  875. const Ch* src_; //!< Current read position.
  876. const Ch* head_; //!< Original head of the string.
  877. const Ch* end_; //!< Past-the-end position.
  878. bool valid_; //!< Whether the parsing is valid.
  879. };
  880. //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence.
  881. template <typename OutputStream>
  882. class PercentEncodeStream {
  883. public:
  884. PercentEncodeStream(OutputStream& os) : os_(os) {}
  885. void Put(char c) { // UTF-8 must be byte
  886. unsigned char u = static_cast<unsigned char>(c);
  887. static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  888. os_.Put('%');
  889. os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u >> 4]));
  890. os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u & 15]));
  891. }
  892. private:
  893. OutputStream& os_;
  894. };
  895. Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_.
  896. Allocator* ownAllocator_; //!< Allocator owned by this Pointer.
  897. Ch* nameBuffer_; //!< A buffer containing all names in tokens.
  898. Token* tokens_; //!< A list of tokens.
  899. size_t tokenCount_; //!< Number of tokens in tokens_.
  900. size_t parseErrorOffset_; //!< Offset in code unit when parsing fail.
  901. PointerParseErrorCode parseErrorCode_; //!< Parsing error code.
  902. };
  903. //! GenericPointer for Value (UTF-8, default allocator).
  904. typedef GenericPointer<Value> Pointer;
  905. //!@name Helper functions for GenericPointer
  906. //@{
  907. //////////////////////////////////////////////////////////////////////////////
  908. template <typename T>
  909. typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::AllocatorType& a) {
  910. return pointer.Create(root, a);
  911. }
  912. template <typename T, typename CharType, size_t N>
  913. typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) {
  914. return GenericPointer<typename T::ValueType>(source, N - 1).Create(root, a);
  915. }
  916. // No allocator parameter
  917. template <typename DocumentType>
  918. typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer) {
  919. return pointer.Create(document);
  920. }
  921. template <typename DocumentType, typename CharType, size_t N>
  922. typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) {
  923. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Create(document);
  924. }
  925. //////////////////////////////////////////////////////////////////////////////
  926. template <typename T>
  927. typename T::ValueType* GetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
  928. return pointer.Get(root, unresolvedTokenIndex);
  929. }
  930. template <typename T>
  931. const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
  932. return pointer.Get(root, unresolvedTokenIndex);
  933. }
  934. template <typename T, typename CharType, size_t N>
  935. typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) {
  936. return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
  937. }
  938. template <typename T, typename CharType, size_t N>
  939. const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) {
  940. return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
  941. }
  942. //////////////////////////////////////////////////////////////////////////////
  943. template <typename T>
  944. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
  945. return pointer.GetWithDefault(root, defaultValue, a);
  946. }
  947. template <typename T>
  948. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
  949. return pointer.GetWithDefault(root, defaultValue, a);
  950. }
  951. #if RAPIDJSON_HAS_STDSTRING
  952. template <typename T>
  953. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
  954. return pointer.GetWithDefault(root, defaultValue, a);
  955. }
  956. #endif
  957. template <typename T, typename T2>
  958. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  959. GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 defaultValue, typename T::AllocatorType& a) {
  960. return pointer.GetWithDefault(root, defaultValue, a);
  961. }
  962. template <typename T, typename CharType, size_t N>
  963. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
  964. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  965. }
  966. template <typename T, typename CharType, size_t N>
  967. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
  968. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  969. }
  970. #if RAPIDJSON_HAS_STDSTRING
  971. template <typename T, typename CharType, size_t N>
  972. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
  973. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  974. }
  975. #endif
  976. template <typename T, typename CharType, size_t N, typename T2>
  977. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  978. GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) {
  979. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  980. }
  981. // No allocator parameter
  982. template <typename DocumentType>
  983. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& defaultValue) {
  984. return pointer.GetWithDefault(document, defaultValue);
  985. }
  986. template <typename DocumentType>
  987. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* defaultValue) {
  988. return pointer.GetWithDefault(document, defaultValue);
  989. }
  990. #if RAPIDJSON_HAS_STDSTRING
  991. template <typename DocumentType>
  992. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& defaultValue) {
  993. return pointer.GetWithDefault(document, defaultValue);
  994. }
  995. #endif
  996. template <typename DocumentType, typename T2>
  997. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  998. GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 defaultValue) {
  999. return pointer.GetWithDefault(document, defaultValue);
  1000. }
  1001. template <typename DocumentType, typename CharType, size_t N>
  1002. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) {
  1003. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1004. }
  1005. template <typename DocumentType, typename CharType, size_t N>
  1006. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) {
  1007. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1008. }
  1009. #if RAPIDJSON_HAS_STDSTRING
  1010. template <typename DocumentType, typename CharType, size_t N>
  1011. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& defaultValue) {
  1012. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1013. }
  1014. #endif
  1015. template <typename DocumentType, typename CharType, size_t N, typename T2>
  1016. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1017. GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) {
  1018. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1019. }
  1020. //////////////////////////////////////////////////////////////////////////////
  1021. template <typename T>
  1022. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
  1023. return pointer.Set(root, value, a);
  1024. }
  1025. template <typename T>
  1026. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) {
  1027. return pointer.Set(root, value, a);
  1028. }
  1029. template <typename T>
  1030. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* value, typename T::AllocatorType& a) {
  1031. return pointer.Set(root, value, a);
  1032. }
  1033. #if RAPIDJSON_HAS_STDSTRING
  1034. template <typename T>
  1035. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
  1036. return pointer.Set(root, value, a);
  1037. }
  1038. #endif
  1039. template <typename T, typename T2>
  1040. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1041. SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 value, typename T::AllocatorType& a) {
  1042. return pointer.Set(root, value, a);
  1043. }
  1044. template <typename T, typename CharType, size_t N>
  1045. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
  1046. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1047. }
  1048. template <typename T, typename CharType, size_t N>
  1049. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) {
  1050. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1051. }
  1052. template <typename T, typename CharType, size_t N>
  1053. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) {
  1054. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1055. }
  1056. #if RAPIDJSON_HAS_STDSTRING
  1057. template <typename T, typename CharType, size_t N>
  1058. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
  1059. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1060. }
  1061. #endif
  1062. template <typename T, typename CharType, size_t N, typename T2>
  1063. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1064. SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) {
  1065. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1066. }
  1067. // No allocator parameter
  1068. template <typename DocumentType>
  1069. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
  1070. return pointer.Set(document, value);
  1071. }
  1072. template <typename DocumentType>
  1073. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& value) {
  1074. return pointer.Set(document, value);
  1075. }
  1076. template <typename DocumentType>
  1077. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* value) {
  1078. return pointer.Set(document, value);
  1079. }
  1080. #if RAPIDJSON_HAS_STDSTRING
  1081. template <typename DocumentType>
  1082. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& value) {
  1083. return pointer.Set(document, value);
  1084. }
  1085. #endif
  1086. template <typename DocumentType, typename T2>
  1087. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1088. SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 value) {
  1089. return pointer.Set(document, value);
  1090. }
  1091. template <typename DocumentType, typename CharType, size_t N>
  1092. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
  1093. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1094. }
  1095. template <typename DocumentType, typename CharType, size_t N>
  1096. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) {
  1097. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1098. }
  1099. template <typename DocumentType, typename CharType, size_t N>
  1100. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) {
  1101. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1102. }
  1103. #if RAPIDJSON_HAS_STDSTRING
  1104. template <typename DocumentType, typename CharType, size_t N>
  1105. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& value) {
  1106. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1107. }
  1108. #endif
  1109. template <typename DocumentType, typename CharType, size_t N, typename T2>
  1110. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1111. SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) {
  1112. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1113. }
  1114. //////////////////////////////////////////////////////////////////////////////
  1115. template <typename T>
  1116. typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
  1117. return pointer.Swap(root, value, a);
  1118. }
  1119. template <typename T, typename CharType, size_t N>
  1120. typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
  1121. return GenericPointer<typename T::ValueType>(source, N - 1).Swap(root, value, a);
  1122. }
  1123. template <typename DocumentType>
  1124. typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
  1125. return pointer.Swap(document, value);
  1126. }
  1127. template <typename DocumentType, typename CharType, size_t N>
  1128. typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
  1129. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Swap(document, value);
  1130. }
  1131. //////////////////////////////////////////////////////////////////////////////
  1132. template <typename T>
  1133. bool EraseValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer) {
  1134. return pointer.Erase(root);
  1135. }
  1136. template <typename T, typename CharType, size_t N>
  1137. bool EraseValueByPointer(T& root, const CharType(&source)[N]) {
  1138. return GenericPointer<typename T::ValueType>(source, N - 1).Erase(root);
  1139. }
  1140. //@}
  1141. RAPIDJSON_NAMESPACE_END
  1142. #if defined(__clang__) || defined(_MSC_VER)
  1143. RAPIDJSON_DIAG_POP
  1144. #endif
  1145. #endif // RAPIDJSON_POINTER_H_