pointer.h 59 KB

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