pointer.h 62 KB

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