pointer.h 62 KB

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