pointer.h 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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. //! Swap the content of this pointer with an other.
  168. /*!
  169. \param other The pointer to swap with.
  170. \note Constant complexity.
  171. */
  172. GenericPointer& Swap(GenericPointer& other) RAPIDJSON_NOEXCEPT {
  173. internal::Swap(allocator_, other.allocator_);
  174. internal::Swap(ownAllocator_, other.ownAllocator_);
  175. internal::Swap(nameBuffer_, other.nameBuffer_);
  176. internal::Swap(tokens_, other.tokens_);
  177. internal::Swap(tokenCount_, other.tokenCount_);
  178. internal::Swap(parseErrorOffset_, other.parseErrorOffset_);
  179. internal::Swap(parseErrorCode_, other.parseErrorCode_);
  180. return *this;
  181. }
  182. //! free-standing swap function helper
  183. /*!
  184. Helper function to enable support for common swap implementation pattern based on \c std::swap:
  185. \code
  186. void swap(MyClass& a, MyClass& b) {
  187. using std::swap;
  188. swap(a.pointer, b.pointer);
  189. // ...
  190. }
  191. \endcode
  192. \see Swap()
  193. */
  194. friend inline void swap(GenericPointer& a, GenericPointer& b) RAPIDJSON_NOEXCEPT { a.Swap(b); }
  195. //@}
  196. //!@name Append token
  197. //@{
  198. //! Append a token and return a new Pointer
  199. /*!
  200. \param token Token to be appended.
  201. \param allocator Allocator for the newly return Pointer.
  202. \return A new Pointer with appended token.
  203. */
  204. GenericPointer Append(const Token& token, Allocator* allocator = 0) const {
  205. GenericPointer r;
  206. r.allocator_ = allocator;
  207. Ch *p = r.CopyFromRaw(*this, 1, token.length + 1);
  208. std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch));
  209. r.tokens_[tokenCount_].name = p;
  210. r.tokens_[tokenCount_].length = token.length;
  211. r.tokens_[tokenCount_].index = token.index;
  212. return r;
  213. }
  214. //! Append a name token with length, and return a new Pointer
  215. /*!
  216. \param name Name to be appended.
  217. \param length Length of name.
  218. \param allocator Allocator for the newly return Pointer.
  219. \return A new Pointer with appended token.
  220. */
  221. GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const {
  222. Token token = { name, length, kPointerInvalidIndex };
  223. return Append(token, allocator);
  224. }
  225. //! Append a name token without length, and return a new Pointer
  226. /*!
  227. \param name Name (const Ch*) to be appended.
  228. \param allocator Allocator for the newly return Pointer.
  229. \return A new Pointer with appended token.
  230. */
  231. template <typename T>
  232. RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer))
  233. Append(T* name, Allocator* allocator = 0) const {
  234. return Append(name, internal::StrLen(name), allocator);
  235. }
  236. #if RAPIDJSON_HAS_STDSTRING
  237. //! Append a name token, and return a new Pointer
  238. /*!
  239. \param name Name to be appended.
  240. \param allocator Allocator for the newly return Pointer.
  241. \return A new Pointer with appended token.
  242. */
  243. GenericPointer Append(const std::basic_string<Ch>& name, Allocator* allocator = 0) const {
  244. return Append(name.c_str(), static_cast<SizeType>(name.size()), allocator);
  245. }
  246. #endif
  247. //! Append a index token, and return a new Pointer
  248. /*!
  249. \param index Index to be appended.
  250. \param allocator Allocator for the newly return Pointer.
  251. \return A new Pointer with appended token.
  252. */
  253. GenericPointer Append(SizeType index, Allocator* allocator = 0) const {
  254. char buffer[21];
  255. char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer);
  256. SizeType length = static_cast<SizeType>(end - buffer);
  257. buffer[length] = '\0';
  258. if (sizeof(Ch) == 1) {
  259. Token token = { reinterpret_cast<Ch*>(buffer), length, index };
  260. return Append(token, allocator);
  261. }
  262. else {
  263. Ch name[21];
  264. for (size_t i = 0; i <= length; i++)
  265. name[i] = static_cast<Ch>(buffer[i]);
  266. Token token = { name, length, index };
  267. return Append(token, allocator);
  268. }
  269. }
  270. //! Append a token by value, and return a new Pointer
  271. /*!
  272. \param token token to be appended.
  273. \param allocator Allocator for the newly return Pointer.
  274. \return A new Pointer with appended token.
  275. */
  276. GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const {
  277. if (token.IsString())
  278. return Append(token.GetString(), token.GetStringLength(), allocator);
  279. else {
  280. RAPIDJSON_ASSERT(token.IsUint64());
  281. RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0));
  282. return Append(static_cast<SizeType>(token.GetUint64()), allocator);
  283. }
  284. }
  285. //!@name Handling Parse Error
  286. //@{
  287. //! Check whether this is a valid pointer.
  288. bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; }
  289. //! Get the parsing error offset in code unit.
  290. size_t GetParseErrorOffset() const { return parseErrorOffset_; }
  291. //! Get the parsing error code.
  292. PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; }
  293. //@}
  294. //! Get the allocator of this pointer.
  295. Allocator& GetAllocator() { return *allocator_; }
  296. //!@name Tokens
  297. //@{
  298. //! Get the token array (const version only).
  299. const Token* GetTokens() const { return tokens_; }
  300. //! Get the number of tokens.
  301. size_t GetTokenCount() const { return tokenCount_; }
  302. //@}
  303. //!@name Equality/inequality operators
  304. //@{
  305. //! Equality operator.
  306. /*!
  307. \note When any pointers are invalid, always returns false.
  308. */
  309. bool operator==(const GenericPointer& rhs) const {
  310. if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_)
  311. return false;
  312. for (size_t i = 0; i < tokenCount_; i++) {
  313. if (tokens_[i].index != rhs.tokens_[i].index ||
  314. tokens_[i].length != rhs.tokens_[i].length ||
  315. (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0))
  316. {
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. //! Inequality operator.
  323. /*!
  324. \note When any pointers are invalid, always returns true.
  325. */
  326. bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); }
  327. //! Less than operator.
  328. /*!
  329. \note Invalid pointers are always greater than valid ones.
  330. */
  331. bool operator<(const GenericPointer& rhs) const {
  332. if (!IsValid())
  333. return false;
  334. if (!rhs.IsValid())
  335. return true;
  336. if (tokenCount_ != rhs.tokenCount_)
  337. return tokenCount_ < rhs.tokenCount_;
  338. for (size_t i = 0; i < tokenCount_; i++) {
  339. if (tokens_[i].index != rhs.tokens_[i].index)
  340. return tokens_[i].index < rhs.tokens_[i].index;
  341. if (tokens_[i].length != rhs.tokens_[i].length)
  342. return tokens_[i].length < rhs.tokens_[i].length;
  343. if (int cmp = std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch) * tokens_[i].length))
  344. return cmp < 0;
  345. }
  346. return false;
  347. }
  348. //@}
  349. //!@name Stringify
  350. //@{
  351. //! Stringify the pointer into string representation.
  352. /*!
  353. \tparam OutputStream Type of output stream.
  354. \param os The output stream.
  355. */
  356. template<typename OutputStream>
  357. bool Stringify(OutputStream& os) const {
  358. return Stringify<false, OutputStream>(os);
  359. }
  360. //! Stringify the pointer into URI fragment representation.
  361. /*!
  362. \tparam OutputStream Type of output stream.
  363. \param os The output stream.
  364. */
  365. template<typename OutputStream>
  366. bool StringifyUriFragment(OutputStream& os) const {
  367. return Stringify<true, OutputStream>(os);
  368. }
  369. //@}
  370. //!@name Create value
  371. //@{
  372. //! Create a value in a subtree.
  373. /*!
  374. If the value is not exist, it creates all parent values and a JSON Null value.
  375. So it always succeed and return the newly created or existing value.
  376. Remind that it may change types of parents according to tokens, so it
  377. potentially removes previously stored values. For example, if a document
  378. was an array, and "/foo" is used to create a value, then the document
  379. will be changed to an object, and all existing array elements are lost.
  380. \param root Root value of a DOM subtree to be resolved. It can be any value other than document root.
  381. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  382. \param alreadyExist If non-null, it stores whether the resolved value is already exist.
  383. \return The resolved newly created (a JSON Null value), or already exists value.
  384. */
  385. ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const {
  386. RAPIDJSON_ASSERT(IsValid());
  387. ValueType* v = &root;
  388. bool exist = true;
  389. for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  390. if (v->IsArray() && t->name[0] == '-' && t->length == 1) {
  391. v->PushBack(ValueType().Move(), allocator);
  392. v = &((*v)[v->Size() - 1]);
  393. exist = false;
  394. }
  395. else {
  396. if (t->index == kPointerInvalidIndex) { // must be object name
  397. if (!v->IsObject())
  398. v->SetObject(); // Change to Object
  399. }
  400. else { // object name or array index
  401. if (!v->IsArray() && !v->IsObject())
  402. v->SetArray(); // Change to Array
  403. }
  404. if (v->IsArray()) {
  405. if (t->index >= v->Size()) {
  406. v->Reserve(t->index + 1, allocator);
  407. while (t->index >= v->Size())
  408. v->PushBack(ValueType().Move(), allocator);
  409. exist = false;
  410. }
  411. v = &((*v)[t->index]);
  412. }
  413. else {
  414. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  415. if (m == v->MemberEnd()) {
  416. v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator);
  417. v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end
  418. exist = false;
  419. }
  420. else
  421. v = &m->value;
  422. }
  423. }
  424. }
  425. if (alreadyExist)
  426. *alreadyExist = exist;
  427. return *v;
  428. }
  429. //! Creates a value in a document.
  430. /*!
  431. \param document A document to be resolved.
  432. \param alreadyExist If non-null, it stores whether the resolved value is already exist.
  433. \return The resolved newly created, or already exists value.
  434. */
  435. template <typename stackAllocator>
  436. ValueType& Create(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, bool* alreadyExist = 0) const {
  437. return Create(document, document.GetAllocator(), alreadyExist);
  438. }
  439. //@}
  440. //!@name Query value
  441. //@{
  442. //! Query a value in a subtree.
  443. /*!
  444. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  445. \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token.
  446. \return Pointer to the value if it can be resolved. Otherwise null.
  447. \note
  448. There are only 3 situations when a value cannot be resolved:
  449. 1. A value in the path is not an array nor object.
  450. 2. An object value does not contain the token.
  451. 3. A token is out of range of an array value.
  452. Use unresolvedTokenIndex to retrieve the token index.
  453. */
  454. ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const {
  455. RAPIDJSON_ASSERT(IsValid());
  456. ValueType* v = &root;
  457. for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  458. switch (v->GetType()) {
  459. case kObjectType:
  460. {
  461. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  462. if (m == v->MemberEnd())
  463. break;
  464. v = &m->value;
  465. }
  466. continue;
  467. case kArrayType:
  468. if (t->index == kPointerInvalidIndex || t->index >= v->Size())
  469. break;
  470. v = &((*v)[t->index]);
  471. continue;
  472. default:
  473. break;
  474. }
  475. // Error: unresolved token
  476. if (unresolvedTokenIndex)
  477. *unresolvedTokenIndex = static_cast<size_t>(t - tokens_);
  478. return 0;
  479. }
  480. return v;
  481. }
  482. //! Query a const value in a const subtree.
  483. /*!
  484. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  485. \return Pointer to the value if it can be resolved. Otherwise null.
  486. */
  487. const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const {
  488. return Get(const_cast<ValueType&>(root), unresolvedTokenIndex);
  489. }
  490. //@}
  491. //!@name Query a value with default
  492. //@{
  493. //! Query a value in a subtree with default value.
  494. /*!
  495. Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value.
  496. So that this function always succeed.
  497. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  498. \param defaultValue Default value to be cloned if the value was not exists.
  499. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  500. \see Create()
  501. */
  502. ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const {
  503. bool alreadyExist;
  504. ValueType& v = Create(root, allocator, &alreadyExist);
  505. return alreadyExist ? v : v.CopyFrom(defaultValue, allocator);
  506. }
  507. //! Query a value in a subtree with default null-terminated string.
  508. ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const {
  509. bool alreadyExist;
  510. ValueType& v = Create(root, allocator, &alreadyExist);
  511. return alreadyExist ? v : v.SetString(defaultValue, allocator);
  512. }
  513. #if RAPIDJSON_HAS_STDSTRING
  514. //! Query a value in a subtree with default std::basic_string.
  515. ValueType& GetWithDefault(ValueType& root, const std::basic_string<Ch>& defaultValue, typename ValueType::AllocatorType& allocator) const {
  516. bool alreadyExist;
  517. ValueType& v = Create(root, allocator, &alreadyExist);
  518. return alreadyExist ? v : v.SetString(defaultValue, allocator);
  519. }
  520. #endif
  521. //! Query a value in a subtree with default primitive value.
  522. /*!
  523. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  524. */
  525. template <typename T>
  526. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  527. GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const {
  528. return GetWithDefault(root, ValueType(defaultValue).Move(), allocator);
  529. }
  530. //! Query a value in a document with default value.
  531. template <typename stackAllocator>
  532. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& defaultValue) const {
  533. return GetWithDefault(document, defaultValue, document.GetAllocator());
  534. }
  535. //! Query a value in a document with default null-terminated string.
  536. template <typename stackAllocator>
  537. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* defaultValue) const {
  538. return GetWithDefault(document, defaultValue, document.GetAllocator());
  539. }
  540. #if RAPIDJSON_HAS_STDSTRING
  541. //! Query a value in a document with default std::basic_string.
  542. template <typename stackAllocator>
  543. ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& defaultValue) const {
  544. return GetWithDefault(document, defaultValue, document.GetAllocator());
  545. }
  546. #endif
  547. //! Query a value in a document with default primitive value.
  548. /*!
  549. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  550. */
  551. template <typename T, typename stackAllocator>
  552. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  553. GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T defaultValue) const {
  554. return GetWithDefault(document, defaultValue, document.GetAllocator());
  555. }
  556. //@}
  557. //!@name Set a value
  558. //@{
  559. //! Set a value in a subtree, with move semantics.
  560. /*!
  561. It creates all parents if they are not exist or types are different to the tokens.
  562. So this function always succeeds but potentially remove existing values.
  563. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  564. \param value Value to be set.
  565. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  566. \see Create()
  567. */
  568. ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
  569. return Create(root, allocator) = value;
  570. }
  571. //! Set a value in a subtree, with copy semantics.
  572. ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const {
  573. return Create(root, allocator).CopyFrom(value, allocator);
  574. }
  575. //! Set a null-terminated string in a subtree.
  576. ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const {
  577. return Create(root, allocator) = ValueType(value, allocator).Move();
  578. }
  579. #if RAPIDJSON_HAS_STDSTRING
  580. //! Set a std::basic_string in a subtree.
  581. ValueType& Set(ValueType& root, const std::basic_string<Ch>& value, typename ValueType::AllocatorType& allocator) const {
  582. return Create(root, allocator) = ValueType(value, allocator).Move();
  583. }
  584. #endif
  585. //! Set a primitive value in a subtree.
  586. /*!
  587. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  588. */
  589. template <typename T>
  590. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  591. Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const {
  592. return Create(root, allocator) = ValueType(value).Move();
  593. }
  594. //! Set a value in a document, with move semantics.
  595. template <typename stackAllocator>
  596. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
  597. return Create(document) = value;
  598. }
  599. //! Set a value in a document, with copy semantics.
  600. template <typename stackAllocator>
  601. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& value) const {
  602. return Create(document).CopyFrom(value, document.GetAllocator());
  603. }
  604. //! Set a null-terminated string in a document.
  605. template <typename stackAllocator>
  606. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* value) const {
  607. return Create(document) = ValueType(value, document.GetAllocator()).Move();
  608. }
  609. #if RAPIDJSON_HAS_STDSTRING
  610. //! Sets a std::basic_string in a document.
  611. template <typename stackAllocator>
  612. ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& value) const {
  613. return Create(document) = ValueType(value, document.GetAllocator()).Move();
  614. }
  615. #endif
  616. //! Set a primitive value in a document.
  617. /*!
  618. \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
  619. */
  620. template <typename T, typename stackAllocator>
  621. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
  622. Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T value) const {
  623. return Create(document) = value;
  624. }
  625. //@}
  626. //!@name Swap a value
  627. //@{
  628. //! Swap a value with a value in a subtree.
  629. /*!
  630. It creates all parents if they are not exist or types are different to the tokens.
  631. So this function always succeeds but potentially remove existing values.
  632. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  633. \param value Value to be swapped.
  634. \param allocator Allocator for creating the values if the specified value or its parents are not exist.
  635. \see Create()
  636. */
  637. ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
  638. return Create(root, allocator).Swap(value);
  639. }
  640. //! Swap a value with a value in a document.
  641. template <typename stackAllocator>
  642. ValueType& Swap(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
  643. return Create(document).Swap(value);
  644. }
  645. //@}
  646. //! Erase a value in a subtree.
  647. /*!
  648. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
  649. \return Whether the resolved value is found and erased.
  650. \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false.
  651. */
  652. bool Erase(ValueType& root) const {
  653. RAPIDJSON_ASSERT(IsValid());
  654. if (tokenCount_ == 0) // Cannot erase the root
  655. return false;
  656. ValueType* v = &root;
  657. const Token* last = tokens_ + (tokenCount_ - 1);
  658. for (const Token *t = tokens_; t != last; ++t) {
  659. switch (v->GetType()) {
  660. case kObjectType:
  661. {
  662. typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
  663. if (m == v->MemberEnd())
  664. return false;
  665. v = &m->value;
  666. }
  667. break;
  668. case kArrayType:
  669. if (t->index == kPointerInvalidIndex || t->index >= v->Size())
  670. return false;
  671. v = &((*v)[t->index]);
  672. break;
  673. default:
  674. return false;
  675. }
  676. }
  677. switch (v->GetType()) {
  678. case kObjectType:
  679. return v->EraseMember(GenericStringRef<Ch>(last->name, last->length));
  680. case kArrayType:
  681. if (last->index == kPointerInvalidIndex || last->index >= v->Size())
  682. return false;
  683. v->Erase(v->Begin() + last->index);
  684. return true;
  685. default:
  686. return false;
  687. }
  688. }
  689. private:
  690. //! Clone the content from rhs to this.
  691. /*!
  692. \param rhs Source pointer.
  693. \param extraToken Extra tokens to be allocated.
  694. \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated.
  695. \return Start of non-occupied name buffer, for storing extra names.
  696. */
  697. Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) {
  698. if (!allocator_) // allocator is independently owned.
  699. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
  700. size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens
  701. for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t)
  702. nameBufferSize += t->length;
  703. tokenCount_ = rhs.tokenCount_ + extraToken;
  704. tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch)));
  705. nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
  706. if (rhs.tokenCount_ > 0) {
  707. std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token));
  708. }
  709. if (nameBufferSize > 0) {
  710. std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch));
  711. }
  712. // Adjust pointers to name buffer
  713. std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_;
  714. for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t)
  715. t->name += diff;
  716. return nameBuffer_ + nameBufferSize;
  717. }
  718. //! Check whether a character should be percent-encoded.
  719. /*!
  720. According to RFC 3986 2.3 Unreserved Characters.
  721. \param c The character (code unit) to be tested.
  722. */
  723. bool NeedPercentEncode(Ch c) const {
  724. return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~');
  725. }
  726. //! Parse a JSON String or its URI fragment representation into tokens.
  727. #ifndef __clang__ // -Wdocumentation
  728. /*!
  729. \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated.
  730. \param length Length of the source string.
  731. \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped.
  732. */
  733. #endif
  734. void Parse(const Ch* source, size_t length) {
  735. RAPIDJSON_ASSERT(source != NULL);
  736. RAPIDJSON_ASSERT(nameBuffer_ == 0);
  737. RAPIDJSON_ASSERT(tokens_ == 0);
  738. // Create own allocator if user did not supply.
  739. if (!allocator_)
  740. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
  741. // Count number of '/' as tokenCount
  742. tokenCount_ = 0;
  743. for (const Ch* s = source; s != source + length; s++)
  744. if (*s == '/')
  745. tokenCount_++;
  746. Token* token = tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch)));
  747. Ch* name = nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
  748. size_t i = 0;
  749. // Detect if it is a URI fragment
  750. bool uriFragment = false;
  751. if (source[i] == '#') {
  752. uriFragment = true;
  753. i++;
  754. }
  755. if (i != length && source[i] != '/') {
  756. parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus;
  757. goto error;
  758. }
  759. while (i < length) {
  760. RAPIDJSON_ASSERT(source[i] == '/');
  761. i++; // consumes '/'
  762. token->name = name;
  763. bool isNumber = true;
  764. while (i < length && source[i] != '/') {
  765. Ch c = source[i];
  766. if (uriFragment) {
  767. // Decoding percent-encoding for URI fragment
  768. if (c == '%') {
  769. PercentDecodeStream is(&source[i], source + length);
  770. GenericInsituStringStream<EncodingType> os(name);
  771. Ch* begin = os.PutBegin();
  772. if (!Transcoder<UTF8<>, EncodingType>().Validate(is, os) || !is.IsValid()) {
  773. parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding;
  774. goto error;
  775. }
  776. size_t len = os.PutEnd(begin);
  777. i += is.Tell() - 1;
  778. if (len == 1)
  779. c = *name;
  780. else {
  781. name += len;
  782. isNumber = false;
  783. i++;
  784. continue;
  785. }
  786. }
  787. else if (NeedPercentEncode(c)) {
  788. parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode;
  789. goto error;
  790. }
  791. }
  792. i++;
  793. // Escaping "~0" -> '~', "~1" -> '/'
  794. if (c == '~') {
  795. if (i < length) {
  796. c = source[i];
  797. if (c == '0') c = '~';
  798. else if (c == '1') c = '/';
  799. else {
  800. parseErrorCode_ = kPointerParseErrorInvalidEscape;
  801. goto error;
  802. }
  803. i++;
  804. }
  805. else {
  806. parseErrorCode_ = kPointerParseErrorInvalidEscape;
  807. goto error;
  808. }
  809. }
  810. // First check for index: all of characters are digit
  811. if (c < '0' || c > '9')
  812. isNumber = false;
  813. *name++ = c;
  814. }
  815. token->length = static_cast<SizeType>(name - token->name);
  816. if (token->length == 0)
  817. isNumber = false;
  818. *name++ = '\0'; // Null terminator
  819. // Second check for index: more than one digit cannot have leading zero
  820. if (isNumber && token->length > 1 && token->name[0] == '0')
  821. isNumber = false;
  822. // String to SizeType conversion
  823. SizeType n = 0;
  824. if (isNumber) {
  825. for (size_t j = 0; j < token->length; j++) {
  826. SizeType m = n * 10 + static_cast<SizeType>(token->name[j] - '0');
  827. if (m < n) { // overflow detection
  828. isNumber = false;
  829. break;
  830. }
  831. n = m;
  832. }
  833. }
  834. token->index = isNumber ? n : kPointerInvalidIndex;
  835. token++;
  836. }
  837. RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer
  838. parseErrorCode_ = kPointerParseErrorNone;
  839. return;
  840. error:
  841. Allocator::Free(tokens_);
  842. nameBuffer_ = 0;
  843. tokens_ = 0;
  844. tokenCount_ = 0;
  845. parseErrorOffset_ = i;
  846. return;
  847. }
  848. //! Stringify to string or URI fragment representation.
  849. /*!
  850. \tparam uriFragment True for stringifying to URI fragment representation. False for string representation.
  851. \tparam OutputStream type of output stream.
  852. \param os The output stream.
  853. */
  854. template<bool uriFragment, typename OutputStream>
  855. bool Stringify(OutputStream& os) const {
  856. RAPIDJSON_ASSERT(IsValid());
  857. if (uriFragment)
  858. os.Put('#');
  859. for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
  860. os.Put('/');
  861. for (size_t j = 0; j < t->length; j++) {
  862. Ch c = t->name[j];
  863. if (c == '~') {
  864. os.Put('~');
  865. os.Put('0');
  866. }
  867. else if (c == '/') {
  868. os.Put('~');
  869. os.Put('1');
  870. }
  871. else if (uriFragment && NeedPercentEncode(c)) {
  872. // Transcode to UTF8 sequence
  873. GenericStringStream<typename ValueType::EncodingType> source(&t->name[j]);
  874. PercentEncodeStream<OutputStream> target(os);
  875. if (!Transcoder<EncodingType, UTF8<> >().Validate(source, target))
  876. return false;
  877. j += source.Tell() - 1;
  878. }
  879. else
  880. os.Put(c);
  881. }
  882. }
  883. return true;
  884. }
  885. //! A helper stream for decoding a percent-encoded sequence into code unit.
  886. /*!
  887. This stream decodes %XY triplet into code unit (0-255).
  888. If it encounters invalid characters, it sets output code unit as 0 and
  889. mark invalid, and to be checked by IsValid().
  890. */
  891. class PercentDecodeStream {
  892. public:
  893. typedef typename ValueType::Ch Ch;
  894. //! Constructor
  895. /*!
  896. \param source Start of the stream
  897. \param end Past-the-end of the stream.
  898. */
  899. PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {}
  900. Ch Take() {
  901. if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet
  902. valid_ = false;
  903. return 0;
  904. }
  905. src_++;
  906. Ch c = 0;
  907. for (int j = 0; j < 2; j++) {
  908. c = static_cast<Ch>(c << 4);
  909. Ch h = *src_;
  910. if (h >= '0' && h <= '9') c = static_cast<Ch>(c + h - '0');
  911. else if (h >= 'A' && h <= 'F') c = static_cast<Ch>(c + h - 'A' + 10);
  912. else if (h >= 'a' && h <= 'f') c = static_cast<Ch>(c + h - 'a' + 10);
  913. else {
  914. valid_ = false;
  915. return 0;
  916. }
  917. src_++;
  918. }
  919. return c;
  920. }
  921. size_t Tell() const { return static_cast<size_t>(src_ - head_); }
  922. bool IsValid() const { return valid_; }
  923. private:
  924. const Ch* src_; //!< Current read position.
  925. const Ch* head_; //!< Original head of the string.
  926. const Ch* end_; //!< Past-the-end position.
  927. bool valid_; //!< Whether the parsing is valid.
  928. };
  929. //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence.
  930. template <typename OutputStream>
  931. class PercentEncodeStream {
  932. public:
  933. PercentEncodeStream(OutputStream& os) : os_(os) {}
  934. void Put(char c) { // UTF-8 must be byte
  935. unsigned char u = static_cast<unsigned char>(c);
  936. static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  937. os_.Put('%');
  938. os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u >> 4]));
  939. os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u & 15]));
  940. }
  941. private:
  942. OutputStream& os_;
  943. };
  944. Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_.
  945. Allocator* ownAllocator_; //!< Allocator owned by this Pointer.
  946. Ch* nameBuffer_; //!< A buffer containing all names in tokens.
  947. Token* tokens_; //!< A list of tokens.
  948. size_t tokenCount_; //!< Number of tokens in tokens_.
  949. size_t parseErrorOffset_; //!< Offset in code unit when parsing fail.
  950. PointerParseErrorCode parseErrorCode_; //!< Parsing error code.
  951. };
  952. //! GenericPointer for Value (UTF-8, default allocator).
  953. typedef GenericPointer<Value> Pointer;
  954. //!@name Helper functions for GenericPointer
  955. //@{
  956. //////////////////////////////////////////////////////////////////////////////
  957. template <typename T>
  958. typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::AllocatorType& a) {
  959. return pointer.Create(root, a);
  960. }
  961. template <typename T, typename CharType, size_t N>
  962. typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) {
  963. return GenericPointer<typename T::ValueType>(source, N - 1).Create(root, a);
  964. }
  965. // No allocator parameter
  966. template <typename DocumentType>
  967. typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer) {
  968. return pointer.Create(document);
  969. }
  970. template <typename DocumentType, typename CharType, size_t N>
  971. typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) {
  972. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Create(document);
  973. }
  974. //////////////////////////////////////////////////////////////////////////////
  975. template <typename T>
  976. typename T::ValueType* GetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
  977. return pointer.Get(root, unresolvedTokenIndex);
  978. }
  979. template <typename T>
  980. const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
  981. return pointer.Get(root, unresolvedTokenIndex);
  982. }
  983. template <typename T, typename CharType, size_t N>
  984. typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) {
  985. return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
  986. }
  987. template <typename T, typename CharType, size_t N>
  988. const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) {
  989. return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
  990. }
  991. //////////////////////////////////////////////////////////////////////////////
  992. template <typename T>
  993. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
  994. return pointer.GetWithDefault(root, defaultValue, a);
  995. }
  996. template <typename T>
  997. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
  998. return pointer.GetWithDefault(root, defaultValue, a);
  999. }
  1000. #if RAPIDJSON_HAS_STDSTRING
  1001. template <typename T>
  1002. typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
  1003. return pointer.GetWithDefault(root, defaultValue, a);
  1004. }
  1005. #endif
  1006. template <typename T, typename T2>
  1007. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1008. GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 defaultValue, typename T::AllocatorType& a) {
  1009. return pointer.GetWithDefault(root, defaultValue, a);
  1010. }
  1011. template <typename T, typename CharType, size_t N>
  1012. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
  1013. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  1014. }
  1015. template <typename T, typename CharType, size_t N>
  1016. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
  1017. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  1018. }
  1019. #if RAPIDJSON_HAS_STDSTRING
  1020. template <typename T, typename CharType, size_t N>
  1021. typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
  1022. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  1023. }
  1024. #endif
  1025. template <typename T, typename CharType, size_t N, typename T2>
  1026. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1027. GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) {
  1028. return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
  1029. }
  1030. // No allocator parameter
  1031. template <typename DocumentType>
  1032. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& defaultValue) {
  1033. return pointer.GetWithDefault(document, defaultValue);
  1034. }
  1035. template <typename DocumentType>
  1036. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* defaultValue) {
  1037. return pointer.GetWithDefault(document, defaultValue);
  1038. }
  1039. #if RAPIDJSON_HAS_STDSTRING
  1040. template <typename DocumentType>
  1041. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& defaultValue) {
  1042. return pointer.GetWithDefault(document, defaultValue);
  1043. }
  1044. #endif
  1045. template <typename DocumentType, typename T2>
  1046. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1047. GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 defaultValue) {
  1048. return pointer.GetWithDefault(document, defaultValue);
  1049. }
  1050. template <typename DocumentType, typename CharType, size_t N>
  1051. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) {
  1052. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1053. }
  1054. template <typename DocumentType, typename CharType, size_t N>
  1055. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) {
  1056. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1057. }
  1058. #if RAPIDJSON_HAS_STDSTRING
  1059. template <typename DocumentType, typename CharType, size_t N>
  1060. typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& defaultValue) {
  1061. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1062. }
  1063. #endif
  1064. template <typename DocumentType, typename CharType, size_t N, typename T2>
  1065. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1066. GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) {
  1067. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
  1068. }
  1069. //////////////////////////////////////////////////////////////////////////////
  1070. template <typename T>
  1071. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
  1072. return pointer.Set(root, value, a);
  1073. }
  1074. template <typename T>
  1075. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) {
  1076. return pointer.Set(root, value, a);
  1077. }
  1078. template <typename T>
  1079. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* value, typename T::AllocatorType& a) {
  1080. return pointer.Set(root, value, a);
  1081. }
  1082. #if RAPIDJSON_HAS_STDSTRING
  1083. template <typename T>
  1084. typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
  1085. return pointer.Set(root, value, a);
  1086. }
  1087. #endif
  1088. template <typename T, typename T2>
  1089. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1090. SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 value, typename T::AllocatorType& a) {
  1091. return pointer.Set(root, value, a);
  1092. }
  1093. template <typename T, typename CharType, size_t N>
  1094. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
  1095. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1096. }
  1097. template <typename T, typename CharType, size_t N>
  1098. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) {
  1099. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1100. }
  1101. template <typename T, typename CharType, size_t N>
  1102. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) {
  1103. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1104. }
  1105. #if RAPIDJSON_HAS_STDSTRING
  1106. template <typename T, typename CharType, size_t N>
  1107. typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
  1108. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1109. }
  1110. #endif
  1111. template <typename T, typename CharType, size_t N, typename T2>
  1112. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
  1113. SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) {
  1114. return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
  1115. }
  1116. // No allocator parameter
  1117. template <typename DocumentType>
  1118. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
  1119. return pointer.Set(document, value);
  1120. }
  1121. template <typename DocumentType>
  1122. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& value) {
  1123. return pointer.Set(document, value);
  1124. }
  1125. template <typename DocumentType>
  1126. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* value) {
  1127. return pointer.Set(document, value);
  1128. }
  1129. #if RAPIDJSON_HAS_STDSTRING
  1130. template <typename DocumentType>
  1131. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& value) {
  1132. return pointer.Set(document, value);
  1133. }
  1134. #endif
  1135. template <typename DocumentType, typename T2>
  1136. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1137. SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 value) {
  1138. return pointer.Set(document, value);
  1139. }
  1140. template <typename DocumentType, typename CharType, size_t N>
  1141. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
  1142. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1143. }
  1144. template <typename DocumentType, typename CharType, size_t N>
  1145. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) {
  1146. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1147. }
  1148. template <typename DocumentType, typename CharType, size_t N>
  1149. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) {
  1150. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1151. }
  1152. #if RAPIDJSON_HAS_STDSTRING
  1153. template <typename DocumentType, typename CharType, size_t N>
  1154. typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& value) {
  1155. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1156. }
  1157. #endif
  1158. template <typename DocumentType, typename CharType, size_t N, typename T2>
  1159. RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
  1160. SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) {
  1161. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
  1162. }
  1163. //////////////////////////////////////////////////////////////////////////////
  1164. template <typename T>
  1165. typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
  1166. return pointer.Swap(root, value, a);
  1167. }
  1168. template <typename T, typename CharType, size_t N>
  1169. typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
  1170. return GenericPointer<typename T::ValueType>(source, N - 1).Swap(root, value, a);
  1171. }
  1172. template <typename DocumentType>
  1173. typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
  1174. return pointer.Swap(document, value);
  1175. }
  1176. template <typename DocumentType, typename CharType, size_t N>
  1177. typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
  1178. return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Swap(document, value);
  1179. }
  1180. //////////////////////////////////////////////////////////////////////////////
  1181. template <typename T>
  1182. bool EraseValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer) {
  1183. return pointer.Erase(root);
  1184. }
  1185. template <typename T, typename CharType, size_t N>
  1186. bool EraseValueByPointer(T& root, const CharType(&source)[N]) {
  1187. return GenericPointer<typename T::ValueType>(source, N - 1).Erase(root);
  1188. }
  1189. //@}
  1190. RAPIDJSON_NAMESPACE_END
  1191. #if defined(__clang__) || defined(_MSC_VER)
  1192. RAPIDJSON_DIAG_POP
  1193. #endif
  1194. #endif // RAPIDJSON_POINTER_H_