You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tinyxml2.cpp 66 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  1. /*
  2. Original code by Lee Thomason (www.grinninglizard.com)
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any
  5. damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any
  7. purpose, including commercial applications, and to alter it and
  8. redistribute it freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must
  10. not claim that you wrote the original software. If you use this
  11. software in a product, an acknowledgment in the product documentation
  12. would be appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and
  14. must not be misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source
  16. distribution.
  17. */
  18. #include "tinyxml2.h"
  19. #include <new> // yes, this one new style header, is in the Android SDK.
  20. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
  21. #include <stdarg.h>
  22. #include <stddef.h>
  23. #else
  24. #include <cstdarg>
  25. #include <cstddef>
  26. #endif
  27. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE)
  28. // Microsoft Visual Studio, version 2005 and higher. Not WinCE.
  29. /*int _snprintf_s(
  30. char *buffer,
  31. size_t sizeOfBuffer,
  32. size_t count,
  33. const char *format [,
  34. argument] ...
  35. );*/
  36. static inline int TIXML_SNPRINTF(char* buffer, size_t size, const char* format, ...)
  37. {
  38. va_list va;
  39. va_start(va, format);
  40. int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va);
  41. va_end(va);
  42. return result;
  43. }
  44. static inline int TIXML_VSNPRINTF(char* buffer, size_t size, const char* format, va_list va)
  45. {
  46. int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va);
  47. return result;
  48. }
  49. #define TIXML_VSCPRINTF _vscprintf
  50. #define TIXML_SSCANF sscanf_s
  51. #elif defined _MSC_VER
  52. // Microsoft Visual Studio 2003 and earlier or WinCE
  53. #define TIXML_SNPRINTF _snprintf
  54. #define TIXML_VSNPRINTF _vsnprintf
  55. #define TIXML_SSCANF sscanf
  56. #if (_MSC_VER < 1400) && (!defined WINCE)
  57. // Microsoft Visual Studio 2003 and not WinCE.
  58. #define TIXML_VSCPRINTF \
  59. _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have.
  60. #else
  61. // Microsoft Visual Studio 2003 and earlier or WinCE.
  62. static inline int TIXML_VSCPRINTF(const char* format, va_list va)
  63. {
  64. int len = 512;
  65. for (;;) {
  66. len = len * 2;
  67. char* str = new char[len]();
  68. const int required = _vsnprintf(str, len, format, va);
  69. delete[] str;
  70. if (required != -1) {
  71. TIXMLASSERT(required >= 0);
  72. len = required;
  73. break;
  74. }
  75. }
  76. TIXMLASSERT(len >= 0);
  77. return len;
  78. }
  79. #endif
  80. #else
  81. // GCC version 3 and higher
  82. // #warning( "Using sn* functions." )
  83. #define TIXML_SNPRINTF snprintf
  84. #define TIXML_VSNPRINTF vsnprintf
  85. static inline int TIXML_VSCPRINTF(const char* format, va_list va)
  86. {
  87. int len = vsnprintf(0, 0, format, va);
  88. TIXMLASSERT(len >= 0);
  89. return len;
  90. }
  91. #define TIXML_SSCANF sscanf
  92. #endif
  93. static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF
  94. static const char LF = LINE_FEED;
  95. static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out
  96. static const char CR = CARRIAGE_RETURN;
  97. static const char SINGLE_QUOTE = '\'';
  98. static const char DOUBLE_QUOTE = '\"';
  99. // Bunch of unicode info at:
  100. // http://www.unicode.org/faq/utf_bom.html
  101. // ef bb bf (Microsoft "lead bytes") - designates UTF-8
  102. static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
  103. static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
  104. static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
  105. namespace tinyxml2 {
  106. struct Entity {
  107. const char* pattern;
  108. int length;
  109. char value;
  110. };
  111. static const int NUM_ENTITIES = 5;
  112. static const Entity entities[NUM_ENTITIES] = {{"quot", 4, DOUBLE_QUOTE},
  113. {"amp", 3, '&'},
  114. {"apos", 4, SINGLE_QUOTE},
  115. {"lt", 2, '<'},
  116. {"gt", 2, '>'}};
  117. StrPair::~StrPair()
  118. {
  119. Reset();
  120. }
  121. void StrPair::TransferTo(StrPair* other)
  122. {
  123. if (this == other) {
  124. return;
  125. }
  126. // This in effect implements the assignment operator by "moving"
  127. // ownership (as in auto_ptr).
  128. TIXMLASSERT(other != 0);
  129. TIXMLASSERT(other->_flags == 0);
  130. TIXMLASSERT(other->_start == 0);
  131. TIXMLASSERT(other->_end == 0);
  132. other->Reset();
  133. other->_flags = _flags;
  134. other->_start = _start;
  135. other->_end = _end;
  136. _flags = 0;
  137. _start = 0;
  138. _end = 0;
  139. }
  140. void StrPair::Reset()
  141. {
  142. if (_flags & NEEDS_DELETE) {
  143. delete[] _start;
  144. }
  145. _flags = 0;
  146. _start = 0;
  147. _end = 0;
  148. }
  149. void StrPair::SetStr(const char* str, int flags)
  150. {
  151. TIXMLASSERT(str);
  152. Reset();
  153. size_t len = strlen(str);
  154. TIXMLASSERT(_start == 0);
  155. _start = new char[len + 1];
  156. memcpy(_start, str, len + 1);
  157. _end = _start + len;
  158. _flags = flags | NEEDS_DELETE;
  159. }
  160. char* StrPair::ParseText(char* p, const char* endTag, int strFlags)
  161. {
  162. TIXMLASSERT(p);
  163. TIXMLASSERT(endTag && *endTag);
  164. char* start = p;
  165. char endChar = *endTag;
  166. size_t length = strlen(endTag);
  167. // Inner loop of text parsing.
  168. while (*p) {
  169. if (*p == endChar && strncmp(p, endTag, length) == 0) {
  170. Set(start, p, strFlags);
  171. return p + length;
  172. }
  173. ++p;
  174. TIXMLASSERT(p);
  175. }
  176. return 0;
  177. }
  178. char* StrPair::ParseName(char* p)
  179. {
  180. if (!p || !(*p)) {
  181. return 0;
  182. }
  183. if (!XMLUtil::IsNameStartChar(*p)) {
  184. return 0;
  185. }
  186. char* const start = p;
  187. ++p;
  188. while (*p && XMLUtil::IsNameChar(*p)) {
  189. ++p;
  190. }
  191. Set(start, p, 0);
  192. return p;
  193. }
  194. void StrPair::CollapseWhitespace()
  195. {
  196. // Adjusting _start would cause undefined behavior on delete[]
  197. TIXMLASSERT((_flags & NEEDS_DELETE) == 0);
  198. // Trim leading space.
  199. _start = XMLUtil::SkipWhiteSpace(_start);
  200. if (*_start) {
  201. const char* p = _start; // the read pointer
  202. char* q = _start; // the write pointer
  203. while (*p) {
  204. if (XMLUtil::IsWhiteSpace(*p)) {
  205. p = XMLUtil::SkipWhiteSpace(p);
  206. if (*p == 0) {
  207. break; // don't write to q; this trims the trailing space.
  208. }
  209. *q = ' ';
  210. ++q;
  211. }
  212. *q = *p;
  213. ++q;
  214. ++p;
  215. }
  216. *q = 0;
  217. }
  218. }
  219. const char* StrPair::GetStr()
  220. {
  221. TIXMLASSERT(_start);
  222. TIXMLASSERT(_end);
  223. if (_flags & NEEDS_FLUSH) {
  224. *_end = 0;
  225. _flags ^= NEEDS_FLUSH;
  226. if (_flags) {
  227. const char* p = _start; // the read pointer
  228. char* q = _start; // the write pointer
  229. while (p < _end) {
  230. if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR) {
  231. // CR-LF pair becomes LF
  232. // CR alone becomes LF
  233. // LF-CR becomes LF
  234. if (*(p + 1) == LF) {
  235. p += 2;
  236. } else {
  237. ++p;
  238. }
  239. *q = LF;
  240. ++q;
  241. } else if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF) {
  242. if (*(p + 1) == CR) {
  243. p += 2;
  244. } else {
  245. ++p;
  246. }
  247. *q = LF;
  248. ++q;
  249. } else if ((_flags & NEEDS_ENTITY_PROCESSING) && *p == '&') {
  250. // Entities handled by tinyXML2:
  251. // - special entities in the entity table [in/out]
  252. // - numeric character reference [in]
  253. // &#20013; or &#x4e2d;
  254. if (*(p + 1) == '#') {
  255. const int buflen = 10;
  256. char buf[buflen] = {0};
  257. int len = 0;
  258. char* adjusted = const_cast<char*>(XMLUtil::GetCharacterRef(p, buf, &len));
  259. if (adjusted == 0) {
  260. *q = *p;
  261. ++p;
  262. ++q;
  263. } else {
  264. TIXMLASSERT(0 <= len && len <= buflen);
  265. TIXMLASSERT(q + len <= adjusted);
  266. p = adjusted;
  267. memcpy(q, buf, len);
  268. q += len;
  269. }
  270. } else {
  271. bool entityFound = false;
  272. for (int i = 0; i < NUM_ENTITIES; ++i) {
  273. const Entity& entity = entities[i];
  274. if (strncmp(p + 1, entity.pattern, entity.length) == 0
  275. && *(p + entity.length + 1) == ';') {
  276. // Found an entity - convert.
  277. *q = entity.value;
  278. ++q;
  279. p += entity.length + 2;
  280. entityFound = true;
  281. break;
  282. }
  283. }
  284. if (!entityFound) {
  285. // fixme: treat as error?
  286. ++p;
  287. ++q;
  288. }
  289. }
  290. } else {
  291. *q = *p;
  292. ++p;
  293. ++q;
  294. }
  295. }
  296. *q = 0;
  297. }
  298. // The loop below has plenty going on, and this
  299. // is a less useful mode. Break it out.
  300. if (_flags & NEEDS_WHITESPACE_COLLAPSING) {
  301. CollapseWhitespace();
  302. }
  303. _flags = (_flags & NEEDS_DELETE);
  304. }
  305. TIXMLASSERT(_start);
  306. return _start;
  307. }
  308. // --------- XMLUtil ----------- //
  309. const char* XMLUtil::ReadBOM(const char* p, bool* bom)
  310. {
  311. TIXMLASSERT(p);
  312. TIXMLASSERT(bom);
  313. *bom = false;
  314. const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
  315. // Check for BOM:
  316. if (*(pu + 0) == TIXML_UTF_LEAD_0 && *(pu + 1) == TIXML_UTF_LEAD_1
  317. && *(pu + 2) == TIXML_UTF_LEAD_2) {
  318. *bom = true;
  319. p += 3;
  320. }
  321. TIXMLASSERT(p);
  322. return p;
  323. }
  324. void XMLUtil::ConvertUTF32ToUTF8(unsigned long input, char* output, int* length)
  325. {
  326. const unsigned long BYTE_MASK = 0xBF;
  327. const unsigned long BYTE_MARK = 0x80;
  328. const unsigned long FIRST_BYTE_MARK[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC};
  329. if (input < 0x80) {
  330. *length = 1;
  331. } else if (input < 0x800) {
  332. *length = 2;
  333. } else if (input < 0x10000) {
  334. *length = 3;
  335. } else if (input < 0x200000) {
  336. *length = 4;
  337. } else {
  338. *length = 0; // This code won't convert this correctly anyway.
  339. return;
  340. }
  341. output += *length;
  342. // Scary scary fall throughs.
  343. switch (*length) {
  344. case 4:
  345. --output;
  346. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  347. input >>= 6;
  348. case 3:
  349. --output;
  350. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  351. input >>= 6;
  352. case 2:
  353. --output;
  354. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  355. input >>= 6;
  356. case 1:
  357. --output;
  358. *output = (char)(input | FIRST_BYTE_MARK[*length]);
  359. break;
  360. default:
  361. TIXMLASSERT(false);
  362. }
  363. }
  364. const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length)
  365. {
  366. // Presume an entity, and pull it out.
  367. *length = 0;
  368. if (*(p + 1) == '#' && *(p + 2)) {
  369. unsigned long ucs = 0;
  370. TIXMLASSERT(sizeof(ucs) >= 4);
  371. ptrdiff_t delta = 0;
  372. unsigned mult = 1;
  373. static const char SEMICOLON = ';';
  374. if (*(p + 2) == 'x') {
  375. // Hexadecimal.
  376. const char* q = p + 3;
  377. if (!(*q)) {
  378. return 0;
  379. }
  380. q = strchr(q, SEMICOLON);
  381. if (!q) {
  382. return 0;
  383. }
  384. TIXMLASSERT(*q == SEMICOLON);
  385. delta = q - p;
  386. --q;
  387. while (*q != 'x') {
  388. unsigned int digit = 0;
  389. if (*q >= '0' && *q <= '9') {
  390. digit = *q - '0';
  391. } else if (*q >= 'a' && *q <= 'f') {
  392. digit = *q - 'a' + 10;
  393. } else if (*q >= 'A' && *q <= 'F') {
  394. digit = *q - 'A' + 10;
  395. } else {
  396. return 0;
  397. }
  398. TIXMLASSERT(digit < 16);
  399. TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit);
  400. const unsigned int digitScaled = mult * digit;
  401. TIXMLASSERT(ucs <= ULONG_MAX - digitScaled);
  402. ucs += digitScaled;
  403. TIXMLASSERT(mult <= UINT_MAX / 16);
  404. mult *= 16;
  405. --q;
  406. }
  407. } else {
  408. // Decimal.
  409. const char* q = p + 2;
  410. if (!(*q)) {
  411. return 0;
  412. }
  413. q = strchr(q, SEMICOLON);
  414. if (!q) {
  415. return 0;
  416. }
  417. TIXMLASSERT(*q == SEMICOLON);
  418. delta = q - p;
  419. --q;
  420. while (*q != '#') {
  421. if (*q >= '0' && *q <= '9') {
  422. const unsigned int digit = *q - '0';
  423. TIXMLASSERT(digit < 10);
  424. TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit);
  425. const unsigned int digitScaled = mult * digit;
  426. TIXMLASSERT(ucs <= ULONG_MAX - digitScaled);
  427. ucs += digitScaled;
  428. } else {
  429. return 0;
  430. }
  431. TIXMLASSERT(mult <= UINT_MAX / 10);
  432. mult *= 10;
  433. --q;
  434. }
  435. }
  436. // convert the UCS to UTF-8
  437. ConvertUTF32ToUTF8(ucs, value, length);
  438. return p + delta + 1;
  439. }
  440. return p + 1;
  441. }
  442. void XMLUtil::ToStr(int v, char* buffer, int bufferSize)
  443. {
  444. TIXML_SNPRINTF(buffer, bufferSize, "%d", v);
  445. }
  446. void XMLUtil::ToStr(unsigned v, char* buffer, int bufferSize)
  447. {
  448. TIXML_SNPRINTF(buffer, bufferSize, "%u", v);
  449. }
  450. void XMLUtil::ToStr(bool v, char* buffer, int bufferSize)
  451. {
  452. TIXML_SNPRINTF(buffer, bufferSize, "%s", v ? "true" : "false");
  453. }
  454. /*
  455. ToStr() of a number is a very tricky topic.
  456. https://github.com/leethomason/tinyxml2/issues/106
  457. */
  458. void XMLUtil::ToStr(float v, char* buffer, int bufferSize)
  459. {
  460. TIXML_SNPRINTF(buffer, bufferSize, "%.8g", v);
  461. }
  462. void XMLUtil::ToStr(double v, char* buffer, int bufferSize)
  463. {
  464. TIXML_SNPRINTF(buffer, bufferSize, "%.17g", v);
  465. }
  466. void XMLUtil::ToStr(int64_t v, char* buffer, int bufferSize)
  467. {
  468. // horrible syntax trick to make the compiler happy about %lld
  469. TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v);
  470. }
  471. bool XMLUtil::ToInt(const char* str, int* value)
  472. {
  473. if (TIXML_SSCANF(str, "%d", value) == 1) {
  474. return true;
  475. }
  476. return false;
  477. }
  478. bool XMLUtil::ToUnsigned(const char* str, unsigned* value)
  479. {
  480. if (TIXML_SSCANF(str, "%u", value) == 1) {
  481. return true;
  482. }
  483. return false;
  484. }
  485. bool XMLUtil::ToBool(const char* str, bool* value)
  486. {
  487. int ival = 0;
  488. if (ToInt(str, &ival)) {
  489. *value = (ival == 0) ? false : true;
  490. return true;
  491. }
  492. if (StringEqual(str, "true")) {
  493. *value = true;
  494. return true;
  495. } else if (StringEqual(str, "false")) {
  496. *value = false;
  497. return true;
  498. }
  499. return false;
  500. }
  501. bool XMLUtil::ToFloat(const char* str, float* value)
  502. {
  503. if (TIXML_SSCANF(str, "%f", value) == 1) {
  504. return true;
  505. }
  506. return false;
  507. }
  508. bool XMLUtil::ToDouble(const char* str, double* value)
  509. {
  510. if (TIXML_SSCANF(str, "%lf", value) == 1) {
  511. return true;
  512. }
  513. return false;
  514. }
  515. bool XMLUtil::ToInt64(const char* str, int64_t* value)
  516. {
  517. long long v = 0; // horrible syntax trick to make the compiler happy about %lld
  518. if (TIXML_SSCANF(str, "%lld", &v) == 1) {
  519. *value = (int64_t)v;
  520. return true;
  521. }
  522. return false;
  523. }
  524. char* XMLDocument::Identify(char* p, XMLNode** node)
  525. {
  526. TIXMLASSERT(node);
  527. TIXMLASSERT(p);
  528. char* const start = p;
  529. p = XMLUtil::SkipWhiteSpace(p);
  530. if (!*p) {
  531. *node = 0;
  532. TIXMLASSERT(p);
  533. return p;
  534. }
  535. // These strings define the matching patterns:
  536. static const char* xmlHeader = {"<?"};
  537. static const char* commentHeader = {"<!--"};
  538. static const char* cdataHeader = {"<![CDATA["};
  539. static const char* dtdHeader = {"<!"};
  540. static const char* elementHeader = {"<"}; // and a header for everything else; check last.
  541. static const int xmlHeaderLen = 2;
  542. static const int commentHeaderLen = 4;
  543. static const int cdataHeaderLen = 9;
  544. static const int dtdHeaderLen = 2;
  545. static const int elementHeaderLen = 1;
  546. TIXMLASSERT(sizeof(XMLComment) == sizeof(XMLUnknown)); // use same memory pool
  547. TIXMLASSERT(sizeof(XMLComment) == sizeof(XMLDeclaration)); // use same memory pool
  548. XMLNode* returnNode = 0;
  549. if (XMLUtil::StringEqual(p, xmlHeader, xmlHeaderLen)) {
  550. TIXMLASSERT(sizeof(XMLDeclaration) == _commentPool.ItemSize());
  551. returnNode = new (_commentPool.Alloc()) XMLDeclaration(this);
  552. returnNode->_memPool = &_commentPool;
  553. p += xmlHeaderLen;
  554. } else if (XMLUtil::StringEqual(p, commentHeader, commentHeaderLen)) {
  555. TIXMLASSERT(sizeof(XMLComment) == _commentPool.ItemSize());
  556. returnNode = new (_commentPool.Alloc()) XMLComment(this);
  557. returnNode->_memPool = &_commentPool;
  558. p += commentHeaderLen;
  559. } else if (XMLUtil::StringEqual(p, cdataHeader, cdataHeaderLen)) {
  560. TIXMLASSERT(sizeof(XMLText) == _textPool.ItemSize());
  561. XMLText* text = new (_textPool.Alloc()) XMLText(this);
  562. returnNode = text;
  563. returnNode->_memPool = &_textPool;
  564. p += cdataHeaderLen;
  565. text->SetCData(true);
  566. } else if (XMLUtil::StringEqual(p, dtdHeader, dtdHeaderLen)) {
  567. TIXMLASSERT(sizeof(XMLUnknown) == _commentPool.ItemSize());
  568. returnNode = new (_commentPool.Alloc()) XMLUnknown(this);
  569. returnNode->_memPool = &_commentPool;
  570. p += dtdHeaderLen;
  571. } else if (XMLUtil::StringEqual(p, elementHeader, elementHeaderLen)) {
  572. TIXMLASSERT(sizeof(XMLElement) == _elementPool.ItemSize());
  573. returnNode = new (_elementPool.Alloc()) XMLElement(this);
  574. returnNode->_memPool = &_elementPool;
  575. p += elementHeaderLen;
  576. } else {
  577. TIXMLASSERT(sizeof(XMLText) == _textPool.ItemSize());
  578. returnNode = new (_textPool.Alloc()) XMLText(this);
  579. returnNode->_memPool = &_textPool;
  580. p = start; // Back it up, all the text counts.
  581. }
  582. TIXMLASSERT(returnNode);
  583. TIXMLASSERT(p);
  584. *node = returnNode;
  585. return p;
  586. }
  587. bool XMLDocument::Accept(XMLVisitor* visitor) const
  588. {
  589. TIXMLASSERT(visitor);
  590. if (visitor->VisitEnter(*this)) {
  591. for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) {
  592. if (!node->Accept(visitor)) {
  593. break;
  594. }
  595. }
  596. }
  597. return visitor->VisitExit(*this);
  598. }
  599. // --------- XMLNode ----------- //
  600. XMLNode::XMLNode(XMLDocument* doc)
  601. : _document(doc)
  602. , _parent(0)
  603. , _firstChild(0)
  604. , _lastChild(0)
  605. , _prev(0)
  606. , _next(0)
  607. , _userData(0)
  608. , _memPool(0)
  609. {}
  610. XMLNode::~XMLNode()
  611. {
  612. DeleteChildren();
  613. if (_parent) {
  614. _parent->Unlink(this);
  615. }
  616. }
  617. const char* XMLNode::Value() const
  618. {
  619. // Edge case: XMLDocuments don't have a Value. Return null.
  620. if (this->ToDocument())
  621. return 0;
  622. return _value.GetStr();
  623. }
  624. void XMLNode::SetValue(const char* str, bool staticMem)
  625. {
  626. if (staticMem) {
  627. _value.SetInternedStr(str);
  628. } else {
  629. _value.SetStr(str);
  630. }
  631. }
  632. void XMLNode::DeleteChildren()
  633. {
  634. while (_firstChild) {
  635. TIXMLASSERT(_lastChild);
  636. DeleteChild(_firstChild);
  637. }
  638. _firstChild = _lastChild = 0;
  639. }
  640. void XMLNode::Unlink(XMLNode* child)
  641. {
  642. TIXMLASSERT(child);
  643. TIXMLASSERT(child->_document == _document);
  644. TIXMLASSERT(child->_parent == this);
  645. if (child == _firstChild) {
  646. _firstChild = _firstChild->_next;
  647. }
  648. if (child == _lastChild) {
  649. _lastChild = _lastChild->_prev;
  650. }
  651. if (child->_prev) {
  652. child->_prev->_next = child->_next;
  653. }
  654. if (child->_next) {
  655. child->_next->_prev = child->_prev;
  656. }
  657. child->_parent = 0;
  658. }
  659. void XMLNode::DeleteChild(XMLNode* node)
  660. {
  661. TIXMLASSERT(node);
  662. TIXMLASSERT(node->_document == _document);
  663. TIXMLASSERT(node->_parent == this);
  664. Unlink(node);
  665. DeleteNode(node);
  666. }
  667. XMLNode* XMLNode::InsertEndChild(XMLNode* addThis)
  668. {
  669. TIXMLASSERT(addThis);
  670. if (addThis->_document != _document) {
  671. TIXMLASSERT(false);
  672. return 0;
  673. }
  674. InsertChildPreamble(addThis);
  675. if (_lastChild) {
  676. TIXMLASSERT(_firstChild);
  677. TIXMLASSERT(_lastChild->_next == 0);
  678. _lastChild->_next = addThis;
  679. addThis->_prev = _lastChild;
  680. _lastChild = addThis;
  681. addThis->_next = 0;
  682. } else {
  683. TIXMLASSERT(_firstChild == 0);
  684. _firstChild = _lastChild = addThis;
  685. addThis->_prev = 0;
  686. addThis->_next = 0;
  687. }
  688. addThis->_parent = this;
  689. return addThis;
  690. }
  691. XMLNode* XMLNode::InsertFirstChild(XMLNode* addThis)
  692. {
  693. TIXMLASSERT(addThis);
  694. if (addThis->_document != _document) {
  695. TIXMLASSERT(false);
  696. return 0;
  697. }
  698. InsertChildPreamble(addThis);
  699. if (_firstChild) {
  700. TIXMLASSERT(_lastChild);
  701. TIXMLASSERT(_firstChild->_prev == 0);
  702. _firstChild->_prev = addThis;
  703. addThis->_next = _firstChild;
  704. _firstChild = addThis;
  705. addThis->_prev = 0;
  706. } else {
  707. TIXMLASSERT(_lastChild == 0);
  708. _firstChild = _lastChild = addThis;
  709. addThis->_prev = 0;
  710. addThis->_next = 0;
  711. }
  712. addThis->_parent = this;
  713. return addThis;
  714. }
  715. XMLNode* XMLNode::InsertAfterChild(XMLNode* afterThis, XMLNode* addThis)
  716. {
  717. TIXMLASSERT(addThis);
  718. if (addThis->_document != _document) {
  719. TIXMLASSERT(false);
  720. return 0;
  721. }
  722. TIXMLASSERT(afterThis);
  723. if (afterThis->_parent != this) {
  724. TIXMLASSERT(false);
  725. return 0;
  726. }
  727. if (afterThis->_next == 0) {
  728. // The last node or the only node.
  729. return InsertEndChild(addThis);
  730. }
  731. InsertChildPreamble(addThis);
  732. addThis->_prev = afterThis;
  733. addThis->_next = afterThis->_next;
  734. afterThis->_next->_prev = addThis;
  735. afterThis->_next = addThis;
  736. addThis->_parent = this;
  737. return addThis;
  738. }
  739. const XMLElement* XMLNode::FirstChildElement(const char* name) const
  740. {
  741. for (const XMLNode* node = _firstChild; node; node = node->_next) {
  742. const XMLElement* element = node->ToElementWithName(name);
  743. if (element) {
  744. return element;
  745. }
  746. }
  747. return 0;
  748. }
  749. const XMLElement* XMLNode::LastChildElement(const char* name) const
  750. {
  751. for (const XMLNode* node = _lastChild; node; node = node->_prev) {
  752. const XMLElement* element = node->ToElementWithName(name);
  753. if (element) {
  754. return element;
  755. }
  756. }
  757. return 0;
  758. }
  759. const XMLElement* XMLNode::NextSiblingElement(const char* name) const
  760. {
  761. for (const XMLNode* node = _next; node; node = node->_next) {
  762. const XMLElement* element = node->ToElementWithName(name);
  763. if (element) {
  764. return element;
  765. }
  766. }
  767. return 0;
  768. }
  769. const XMLElement* XMLNode::PreviousSiblingElement(const char* name) const
  770. {
  771. for (const XMLNode* node = _prev; node; node = node->_prev) {
  772. const XMLElement* element = node->ToElementWithName(name);
  773. if (element) {
  774. return element;
  775. }
  776. }
  777. return 0;
  778. }
  779. char* XMLNode::ParseDeep(char* p, StrPair* parentEnd)
  780. {
  781. // This is a recursive method, but thinking about it "at the current level"
  782. // it is a pretty simple flat list:
  783. // <foo/>
  784. // <!-- comment -->
  785. //
  786. // With a special case:
  787. // <foo>
  788. // </foo>
  789. // <!-- comment -->
  790. //
  791. // Where the closing element (/foo) *must* be the next thing after the opening
  792. // element, and the names must match. BUT the tricky bit is that the closing
  793. // element will be read by the child.
  794. //
  795. // 'endTag' is the end tag for this node, it is returned by a call to a child.
  796. // 'parentEnd' is the end tag for the parent, which is filled in and returned.
  797. while (p && *p) {
  798. XMLNode* node = 0;
  799. p = _document->Identify(p, &node);
  800. TIXMLASSERT(p);
  801. if (node == 0) {
  802. break;
  803. }
  804. StrPair endTag;
  805. p = node->ParseDeep(p, &endTag);
  806. if (!p) {
  807. DeleteNode(node);
  808. if (!_document->Error()) {
  809. _document->SetError(XML_ERROR_PARSING, 0, 0);
  810. }
  811. break;
  812. }
  813. XMLDeclaration* decl = node->ToDeclaration();
  814. if (decl) {
  815. // Declarations are only allowed at document level
  816. bool wellLocated = (ToDocument() != 0);
  817. if (wellLocated) {
  818. // Multiple declarations are allowed but all declarations
  819. // must occur before anything else
  820. for (const XMLNode* existingNode = _document->FirstChild(); existingNode;
  821. existingNode = existingNode->NextSibling()) {
  822. if (!existingNode->ToDeclaration()) {
  823. wellLocated = false;
  824. break;
  825. }
  826. }
  827. }
  828. if (!wellLocated) {
  829. _document->SetError(XML_ERROR_PARSING_DECLARATION, decl->Value(), 0);
  830. DeleteNode(node);
  831. break;
  832. }
  833. }
  834. XMLElement* ele = node->ToElement();
  835. if (ele) {
  836. // We read the end tag. Return it to the parent.
  837. if (ele->ClosingType() == XMLElement::CLOSING) {
  838. if (parentEnd) {
  839. ele->_value.TransferTo(parentEnd);
  840. }
  841. node->_memPool->SetTracked(); // created and then immediately deleted.
  842. DeleteNode(node);
  843. return p;
  844. }
  845. // Handle an end tag returned to this level.
  846. // And handle a bunch of annoying errors.
  847. bool mismatch = false;
  848. if (endTag.Empty()) {
  849. if (ele->ClosingType() == XMLElement::OPEN) {
  850. mismatch = true;
  851. }
  852. } else {
  853. if (ele->ClosingType() != XMLElement::OPEN) {
  854. mismatch = true;
  855. } else if (!XMLUtil::StringEqual(endTag.GetStr(), ele->Name())) {
  856. mismatch = true;
  857. }
  858. }
  859. if (mismatch) {
  860. _document->SetError(XML_ERROR_MISMATCHED_ELEMENT, ele->Name(), 0);
  861. DeleteNode(node);
  862. break;
  863. }
  864. }
  865. InsertEndChild(node);
  866. }
  867. return 0;
  868. }
  869. void XMLNode::DeleteNode(XMLNode* node)
  870. {
  871. if (node == 0) {
  872. return;
  873. }
  874. MemPool* pool = node->_memPool;
  875. node->~XMLNode();
  876. pool->Free(node);
  877. }
  878. void XMLNode::InsertChildPreamble(XMLNode* insertThis) const
  879. {
  880. TIXMLASSERT(insertThis);
  881. TIXMLASSERT(insertThis->_document == _document);
  882. if (insertThis->_parent)
  883. insertThis->_parent->Unlink(insertThis);
  884. else
  885. insertThis->_memPool->SetTracked();
  886. }
  887. const XMLElement* XMLNode::ToElementWithName(const char* name) const
  888. {
  889. const XMLElement* element = this->ToElement();
  890. if (element == 0) {
  891. return 0;
  892. }
  893. if (name == 0) {
  894. return element;
  895. }
  896. if (XMLUtil::StringEqual(element->Name(), name)) {
  897. return element;
  898. }
  899. return 0;
  900. }
  901. // --------- XMLText ---------- //
  902. char* XMLText::ParseDeep(char* p, StrPair*)
  903. {
  904. const char* start = p;
  905. if (this->CData()) {
  906. p = _value.ParseText(p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION);
  907. if (!p) {
  908. _document->SetError(XML_ERROR_PARSING_CDATA, start, 0);
  909. }
  910. return p;
  911. } else {
  912. int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT
  913. : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
  914. if (_document->WhitespaceMode() == COLLAPSE_WHITESPACE) {
  915. flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
  916. }
  917. p = _value.ParseText(p, "<", flags);
  918. if (p && *p) {
  919. return p - 1;
  920. }
  921. if (!p) {
  922. _document->SetError(XML_ERROR_PARSING_TEXT, start, 0);
  923. }
  924. }
  925. return 0;
  926. }
  927. XMLNode* XMLText::ShallowClone(XMLDocument* doc) const
  928. {
  929. if (!doc) {
  930. doc = _document;
  931. }
  932. XMLText* text = doc->NewText(Value()); // fixme: this will always allocate memory. Intern?
  933. text->SetCData(this->CData());
  934. return text;
  935. }
  936. bool XMLText::ShallowEqual(const XMLNode* compare) const
  937. {
  938. const XMLText* text = compare->ToText();
  939. return (text && XMLUtil::StringEqual(text->Value(), Value()));
  940. }
  941. bool XMLText::Accept(XMLVisitor* visitor) const
  942. {
  943. TIXMLASSERT(visitor);
  944. return visitor->Visit(*this);
  945. }
  946. // --------- XMLComment ---------- //
  947. XMLComment::XMLComment(XMLDocument* doc) : XMLNode(doc)
  948. {}
  949. XMLComment::~XMLComment()
  950. {}
  951. char* XMLComment::ParseDeep(char* p, StrPair*)
  952. {
  953. // Comment parses as text.
  954. const char* start = p;
  955. p = _value.ParseText(p, "-->", StrPair::COMMENT);
  956. if (p == 0) {
  957. _document->SetError(XML_ERROR_PARSING_COMMENT, start, 0);
  958. }
  959. return p;
  960. }
  961. XMLNode* XMLComment::ShallowClone(XMLDocument* doc) const
  962. {
  963. if (!doc) {
  964. doc = _document;
  965. }
  966. XMLComment* comment =
  967. doc->NewComment(Value()); // fixme: this will always allocate memory. Intern?
  968. return comment;
  969. }
  970. bool XMLComment::ShallowEqual(const XMLNode* compare) const
  971. {
  972. TIXMLASSERT(compare);
  973. const XMLComment* comment = compare->ToComment();
  974. return (comment && XMLUtil::StringEqual(comment->Value(), Value()));
  975. }
  976. bool XMLComment::Accept(XMLVisitor* visitor) const
  977. {
  978. TIXMLASSERT(visitor);
  979. return visitor->Visit(*this);
  980. }
  981. // --------- XMLDeclaration ---------- //
  982. XMLDeclaration::XMLDeclaration(XMLDocument* doc) : XMLNode(doc)
  983. {}
  984. XMLDeclaration::~XMLDeclaration()
  985. {
  986. // printf( "~XMLDeclaration\n" );
  987. }
  988. char* XMLDeclaration::ParseDeep(char* p, StrPair*)
  989. {
  990. // Declaration parses as text.
  991. const char* start = p;
  992. p = _value.ParseText(p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION);
  993. if (p == 0) {
  994. _document->SetError(XML_ERROR_PARSING_DECLARATION, start, 0);
  995. }
  996. return p;
  997. }
  998. XMLNode* XMLDeclaration::ShallowClone(XMLDocument* doc) const
  999. {
  1000. if (!doc) {
  1001. doc = _document;
  1002. }
  1003. XMLDeclaration* dec =
  1004. doc->NewDeclaration(Value()); // fixme: this will always allocate memory. Intern?
  1005. return dec;
  1006. }
  1007. bool XMLDeclaration::ShallowEqual(const XMLNode* compare) const
  1008. {
  1009. TIXMLASSERT(compare);
  1010. const XMLDeclaration* declaration = compare->ToDeclaration();
  1011. return (declaration && XMLUtil::StringEqual(declaration->Value(), Value()));
  1012. }
  1013. bool XMLDeclaration::Accept(XMLVisitor* visitor) const
  1014. {
  1015. TIXMLASSERT(visitor);
  1016. return visitor->Visit(*this);
  1017. }
  1018. // --------- XMLUnknown ---------- //
  1019. XMLUnknown::XMLUnknown(XMLDocument* doc) : XMLNode(doc)
  1020. {}
  1021. XMLUnknown::~XMLUnknown()
  1022. {}
  1023. char* XMLUnknown::ParseDeep(char* p, StrPair*)
  1024. {
  1025. // Unknown parses as text.
  1026. const char* start = p;
  1027. p = _value.ParseText(p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION);
  1028. if (!p) {
  1029. _document->SetError(XML_ERROR_PARSING_UNKNOWN, start, 0);
  1030. }
  1031. return p;
  1032. }
  1033. XMLNode* XMLUnknown::ShallowClone(XMLDocument* doc) const
  1034. {
  1035. if (!doc) {
  1036. doc = _document;
  1037. }
  1038. XMLUnknown* text = doc->NewUnknown(Value()); // fixme: this will always allocate memory. Intern?
  1039. return text;
  1040. }
  1041. bool XMLUnknown::ShallowEqual(const XMLNode* compare) const
  1042. {
  1043. TIXMLASSERT(compare);
  1044. const XMLUnknown* unknown = compare->ToUnknown();
  1045. return (unknown && XMLUtil::StringEqual(unknown->Value(), Value()));
  1046. }
  1047. bool XMLUnknown::Accept(XMLVisitor* visitor) const
  1048. {
  1049. TIXMLASSERT(visitor);
  1050. return visitor->Visit(*this);
  1051. }
  1052. // --------- XMLAttribute ---------- //
  1053. const char* XMLAttribute::Name() const
  1054. {
  1055. return _name.GetStr();
  1056. }
  1057. const char* XMLAttribute::Value() const
  1058. {
  1059. return _value.GetStr();
  1060. }
  1061. char* XMLAttribute::ParseDeep(char* p, bool processEntities)
  1062. {
  1063. // Parse using the name rules: bug fix, was using ParseText before
  1064. p = _name.ParseName(p);
  1065. if (!p || !*p) {
  1066. return 0;
  1067. }
  1068. // Skip white space before =
  1069. p = XMLUtil::SkipWhiteSpace(p);
  1070. if (*p != '=') {
  1071. return 0;
  1072. }
  1073. ++p; // move up to opening quote
  1074. p = XMLUtil::SkipWhiteSpace(p);
  1075. if (*p != '\"' && *p != '\'') {
  1076. return 0;
  1077. }
  1078. char endTag[2] = {*p, 0};
  1079. ++p; // move past opening quote
  1080. p = _value.ParseText(
  1081. p, endTag,
  1082. processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES);
  1083. return p;
  1084. }
  1085. void XMLAttribute::SetName(const char* n)
  1086. {
  1087. _name.SetStr(n);
  1088. }
  1089. XMLError XMLAttribute::QueryIntValue(int* value) const
  1090. {
  1091. if (XMLUtil::ToInt(Value(), value)) {
  1092. return XML_SUCCESS;
  1093. }
  1094. return XML_WRONG_ATTRIBUTE_TYPE;
  1095. }
  1096. XMLError XMLAttribute::QueryUnsignedValue(unsigned int* value) const
  1097. {
  1098. if (XMLUtil::ToUnsigned(Value(), value)) {
  1099. return XML_SUCCESS;
  1100. }
  1101. return XML_WRONG_ATTRIBUTE_TYPE;
  1102. }
  1103. XMLError XMLAttribute::QueryInt64Value(int64_t* value) const
  1104. {
  1105. if (XMLUtil::ToInt64(Value(), value)) {
  1106. return XML_SUCCESS;
  1107. }
  1108. return XML_WRONG_ATTRIBUTE_TYPE;
  1109. }
  1110. XMLError XMLAttribute::QueryBoolValue(bool* value) const
  1111. {
  1112. if (XMLUtil::ToBool(Value(), value)) {
  1113. return XML_SUCCESS;
  1114. }
  1115. return XML_WRONG_ATTRIBUTE_TYPE;
  1116. }
  1117. XMLError XMLAttribute::QueryFloatValue(float* value) const
  1118. {
  1119. if (XMLUtil::ToFloat(Value(), value)) {
  1120. return XML_SUCCESS;
  1121. }
  1122. return XML_WRONG_ATTRIBUTE_TYPE;
  1123. }
  1124. XMLError XMLAttribute::QueryDoubleValue(double* value) const
  1125. {
  1126. if (XMLUtil::ToDouble(Value(), value)) {
  1127. return XML_SUCCESS;
  1128. }
  1129. return XML_WRONG_ATTRIBUTE_TYPE;
  1130. }
  1131. void XMLAttribute::SetAttribute(const char* v)
  1132. {
  1133. _value.SetStr(v);
  1134. }
  1135. void XMLAttribute::SetAttribute(int v)
  1136. {
  1137. char buf[BUF_SIZE];
  1138. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1139. _value.SetStr(buf);
  1140. }
  1141. void XMLAttribute::SetAttribute(unsigned v)
  1142. {
  1143. char buf[BUF_SIZE];
  1144. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1145. _value.SetStr(buf);
  1146. }
  1147. void XMLAttribute::SetAttribute(int64_t v)
  1148. {
  1149. char buf[BUF_SIZE];
  1150. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1151. _value.SetStr(buf);
  1152. }
  1153. void XMLAttribute::SetAttribute(bool v)
  1154. {
  1155. char buf[BUF_SIZE];
  1156. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1157. _value.SetStr(buf);
  1158. }
  1159. void XMLAttribute::SetAttribute(double v)
  1160. {
  1161. char buf[BUF_SIZE];
  1162. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1163. _value.SetStr(buf);
  1164. }
  1165. void XMLAttribute::SetAttribute(float v)
  1166. {
  1167. char buf[BUF_SIZE];
  1168. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1169. _value.SetStr(buf);
  1170. }
  1171. // --------- XMLElement ---------- //
  1172. XMLElement::XMLElement(XMLDocument* doc) : XMLNode(doc), _closingType(0), _rootAttribute(0)
  1173. {}
  1174. XMLElement::~XMLElement()
  1175. {
  1176. while (_rootAttribute) {
  1177. XMLAttribute* next = _rootAttribute->_next;
  1178. DeleteAttribute(_rootAttribute);
  1179. _rootAttribute = next;
  1180. }
  1181. }
  1182. const XMLAttribute* XMLElement::FindAttribute(const char* name) const
  1183. {
  1184. for (XMLAttribute* a = _rootAttribute; a; a = a->_next) {
  1185. if (XMLUtil::StringEqual(a->Name(), name)) {
  1186. return a;
  1187. }
  1188. }
  1189. return 0;
  1190. }
  1191. const char* XMLElement::Attribute(const char* name, const char* value) const
  1192. {
  1193. const XMLAttribute* a = FindAttribute(name);
  1194. if (!a) {
  1195. return 0;
  1196. }
  1197. if (!value || XMLUtil::StringEqual(a->Value(), value)) {
  1198. return a->Value();
  1199. }
  1200. return 0;
  1201. }
  1202. int XMLElement::IntAttribute(const char* name, int defaultValue) const
  1203. {
  1204. int i = defaultValue;
  1205. QueryIntAttribute(name, &i);
  1206. return i;
  1207. }
  1208. unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const
  1209. {
  1210. unsigned i = defaultValue;
  1211. QueryUnsignedAttribute(name, &i);
  1212. return i;
  1213. }
  1214. int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const
  1215. {
  1216. int64_t i = defaultValue;
  1217. QueryInt64Attribute(name, &i);
  1218. return i;
  1219. }
  1220. bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const
  1221. {
  1222. bool b = defaultValue;
  1223. QueryBoolAttribute(name, &b);
  1224. return b;
  1225. }
  1226. double XMLElement::DoubleAttribute(const char* name, double defaultValue) const
  1227. {
  1228. double d = defaultValue;
  1229. QueryDoubleAttribute(name, &d);
  1230. return d;
  1231. }
  1232. float XMLElement::FloatAttribute(const char* name, float defaultValue) const
  1233. {
  1234. float f = defaultValue;
  1235. QueryFloatAttribute(name, &f);
  1236. return f;
  1237. }
  1238. const char* XMLElement::GetText() const
  1239. {
  1240. if (FirstChild() && FirstChild()->ToText()) {
  1241. return FirstChild()->Value();
  1242. }
  1243. return 0;
  1244. }
  1245. void XMLElement::SetText(const char* inText)
  1246. {
  1247. if (FirstChild() && FirstChild()->ToText())
  1248. FirstChild()->SetValue(inText);
  1249. else {
  1250. XMLText* theText = GetDocument()->NewText(inText);
  1251. InsertFirstChild(theText);
  1252. }
  1253. }
  1254. void XMLElement::SetText(int v)
  1255. {
  1256. char buf[BUF_SIZE];
  1257. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1258. SetText(buf);
  1259. }
  1260. void XMLElement::SetText(unsigned v)
  1261. {
  1262. char buf[BUF_SIZE];
  1263. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1264. SetText(buf);
  1265. }
  1266. void XMLElement::SetText(int64_t v)
  1267. {
  1268. char buf[BUF_SIZE];
  1269. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1270. SetText(buf);
  1271. }
  1272. void XMLElement::SetText(bool v)
  1273. {
  1274. char buf[BUF_SIZE];
  1275. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1276. SetText(buf);
  1277. }
  1278. void XMLElement::SetText(float v)
  1279. {
  1280. char buf[BUF_SIZE];
  1281. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1282. SetText(buf);
  1283. }
  1284. void XMLElement::SetText(double v)
  1285. {
  1286. char buf[BUF_SIZE];
  1287. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1288. SetText(buf);
  1289. }
  1290. XMLError XMLElement::QueryIntText(int* ival) const
  1291. {
  1292. if (FirstChild() && FirstChild()->ToText()) {
  1293. const char* t = FirstChild()->Value();
  1294. if (XMLUtil::ToInt(t, ival)) {
  1295. return XML_SUCCESS;
  1296. }
  1297. return XML_CAN_NOT_CONVERT_TEXT;
  1298. }
  1299. return XML_NO_TEXT_NODE;
  1300. }
  1301. XMLError XMLElement::QueryUnsignedText(unsigned* uval) const
  1302. {
  1303. if (FirstChild() && FirstChild()->ToText()) {
  1304. const char* t = FirstChild()->Value();
  1305. if (XMLUtil::ToUnsigned(t, uval)) {
  1306. return XML_SUCCESS;
  1307. }
  1308. return XML_CAN_NOT_CONVERT_TEXT;
  1309. }
  1310. return XML_NO_TEXT_NODE;
  1311. }
  1312. XMLError XMLElement::QueryInt64Text(int64_t* ival) const
  1313. {
  1314. if (FirstChild() && FirstChild()->ToText()) {
  1315. const char* t = FirstChild()->Value();
  1316. if (XMLUtil::ToInt64(t, ival)) {
  1317. return XML_SUCCESS;
  1318. }
  1319. return XML_CAN_NOT_CONVERT_TEXT;
  1320. }
  1321. return XML_NO_TEXT_NODE;
  1322. }
  1323. XMLError XMLElement::QueryBoolText(bool* bval) const
  1324. {
  1325. if (FirstChild() && FirstChild()->ToText()) {
  1326. const char* t = FirstChild()->Value();
  1327. if (XMLUtil::ToBool(t, bval)) {
  1328. return XML_SUCCESS;
  1329. }
  1330. return XML_CAN_NOT_CONVERT_TEXT;
  1331. }
  1332. return XML_NO_TEXT_NODE;
  1333. }
  1334. XMLError XMLElement::QueryDoubleText(double* dval) const
  1335. {
  1336. if (FirstChild() && FirstChild()->ToText()) {
  1337. const char* t = FirstChild()->Value();
  1338. if (XMLUtil::ToDouble(t, dval)) {
  1339. return XML_SUCCESS;
  1340. }
  1341. return XML_CAN_NOT_CONVERT_TEXT;
  1342. }
  1343. return XML_NO_TEXT_NODE;
  1344. }
  1345. XMLError XMLElement::QueryFloatText(float* fval) const
  1346. {
  1347. if (FirstChild() && FirstChild()->ToText()) {
  1348. const char* t = FirstChild()->Value();
  1349. if (XMLUtil::ToFloat(t, fval)) {
  1350. return XML_SUCCESS;
  1351. }
  1352. return XML_CAN_NOT_CONVERT_TEXT;
  1353. }
  1354. return XML_NO_TEXT_NODE;
  1355. }
  1356. int XMLElement::IntText(int defaultValue) const
  1357. {
  1358. int i = defaultValue;
  1359. QueryIntText(&i);
  1360. return i;
  1361. }
  1362. unsigned XMLElement::UnsignedText(unsigned defaultValue) const
  1363. {
  1364. unsigned i = defaultValue;
  1365. QueryUnsignedText(&i);
  1366. return i;
  1367. }
  1368. int64_t XMLElement::Int64Text(int64_t defaultValue) const
  1369. {
  1370. int64_t i = defaultValue;
  1371. QueryInt64Text(&i);
  1372. return i;
  1373. }
  1374. bool XMLElement::BoolText(bool defaultValue) const
  1375. {
  1376. bool b = defaultValue;
  1377. QueryBoolText(&b);
  1378. return b;
  1379. }
  1380. double XMLElement::DoubleText(double defaultValue) const
  1381. {
  1382. double d = defaultValue;
  1383. QueryDoubleText(&d);
  1384. return d;
  1385. }
  1386. float XMLElement::FloatText(float defaultValue) const
  1387. {
  1388. float f = defaultValue;
  1389. QueryFloatText(&f);
  1390. return f;
  1391. }
  1392. XMLAttribute* XMLElement::FindOrCreateAttribute(const char* name)
  1393. {
  1394. XMLAttribute* last = 0;
  1395. XMLAttribute* attrib = 0;
  1396. for (attrib = _rootAttribute; attrib; last = attrib, attrib = attrib->_next) {
  1397. if (XMLUtil::StringEqual(attrib->Name(), name)) {
  1398. break;
  1399. }
  1400. }
  1401. if (!attrib) {
  1402. attrib = CreateAttribute();
  1403. TIXMLASSERT(attrib);
  1404. if (last) {
  1405. last->_next = attrib;
  1406. } else {
  1407. _rootAttribute = attrib;
  1408. }
  1409. attrib->SetName(name);
  1410. }
  1411. return attrib;
  1412. }
  1413. void XMLElement::DeleteAttribute(const char* name)
  1414. {
  1415. XMLAttribute* prev = 0;
  1416. for (XMLAttribute* a = _rootAttribute; a; a = a->_next) {
  1417. if (XMLUtil::StringEqual(name, a->Name())) {
  1418. if (prev) {
  1419. prev->_next = a->_next;
  1420. } else {
  1421. _rootAttribute = a->_next;
  1422. }
  1423. DeleteAttribute(a);
  1424. break;
  1425. }
  1426. prev = a;
  1427. }
  1428. }
  1429. char* XMLElement::ParseAttributes(char* p)
  1430. {
  1431. const char* start = p;
  1432. XMLAttribute* prevAttribute = 0;
  1433. // Read the attributes.
  1434. while (p) {
  1435. p = XMLUtil::SkipWhiteSpace(p);
  1436. if (!(*p)) {
  1437. _document->SetError(XML_ERROR_PARSING_ELEMENT, start, Name());
  1438. return 0;
  1439. }
  1440. // attribute.
  1441. if (XMLUtil::IsNameStartChar(*p)) {
  1442. XMLAttribute* attrib = CreateAttribute();
  1443. TIXMLASSERT(attrib);
  1444. p = attrib->ParseDeep(p, _document->ProcessEntities());
  1445. if (!p || Attribute(attrib->Name())) {
  1446. DeleteAttribute(attrib);
  1447. _document->SetError(XML_ERROR_PARSING_ATTRIBUTE, start, p);
  1448. return 0;
  1449. }
  1450. // There is a minor bug here: if the attribute in the source xml
  1451. // document is duplicated, it will not be detected and the
  1452. // attribute will be doubly added. However, tracking the 'prevAttribute'
  1453. // avoids re-scanning the attribute list. Preferring performance for
  1454. // now, may reconsider in the future.
  1455. if (prevAttribute) {
  1456. prevAttribute->_next = attrib;
  1457. } else {
  1458. _rootAttribute = attrib;
  1459. }
  1460. prevAttribute = attrib;
  1461. }
  1462. // end of the tag
  1463. else if (*p == '>') {
  1464. ++p;
  1465. break;
  1466. }
  1467. // end of the tag
  1468. else if (*p == '/' && *(p + 1) == '>') {
  1469. _closingType = CLOSED;
  1470. return p + 2; // done; sealed element.
  1471. } else {
  1472. _document->SetError(XML_ERROR_PARSING_ELEMENT, start, p);
  1473. return 0;
  1474. }
  1475. }
  1476. return p;
  1477. }
  1478. void XMLElement::DeleteAttribute(XMLAttribute* attribute)
  1479. {
  1480. if (attribute == 0) {
  1481. return;
  1482. }
  1483. MemPool* pool = attribute->_memPool;
  1484. attribute->~XMLAttribute();
  1485. pool->Free(attribute);
  1486. }
  1487. XMLAttribute* XMLElement::CreateAttribute()
  1488. {
  1489. TIXMLASSERT(sizeof(XMLAttribute) == _document->_attributePool.ItemSize());
  1490. XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute();
  1491. attrib->_memPool = &_document->_attributePool;
  1492. attrib->_memPool->SetTracked();
  1493. return attrib;
  1494. }
  1495. //
  1496. // <ele></ele>
  1497. // <ele>foo<b>bar</b></ele>
  1498. //
  1499. char* XMLElement::ParseDeep(char* p, StrPair* strPair)
  1500. {
  1501. // Read the element name.
  1502. p = XMLUtil::SkipWhiteSpace(p);
  1503. // The closing element is the </element> form. It is
  1504. // parsed just like a regular element then deleted from
  1505. // the DOM.
  1506. if (*p == '/') {
  1507. _closingType = CLOSING;
  1508. ++p;
  1509. }
  1510. p = _value.ParseName(p);
  1511. if (_value.Empty()) {
  1512. return 0;
  1513. }
  1514. p = ParseAttributes(p);
  1515. if (!p || !*p || _closingType) {
  1516. return p;
  1517. }
  1518. p = XMLNode::ParseDeep(p, strPair);
  1519. return p;
  1520. }
  1521. XMLNode* XMLElement::ShallowClone(XMLDocument* doc) const
  1522. {
  1523. if (!doc) {
  1524. doc = _document;
  1525. }
  1526. XMLElement* element =
  1527. doc->NewElement(Value()); // fixme: this will always allocate memory. Intern?
  1528. for (const XMLAttribute* a = FirstAttribute(); a; a = a->Next()) {
  1529. element->SetAttribute(a->Name(),
  1530. a->Value()); // fixme: this will always allocate memory. Intern?
  1531. }
  1532. return element;
  1533. }
  1534. bool XMLElement::ShallowEqual(const XMLNode* compare) const
  1535. {
  1536. TIXMLASSERT(compare);
  1537. const XMLElement* other = compare->ToElement();
  1538. if (other && XMLUtil::StringEqual(other->Name(), Name())) {
  1539. const XMLAttribute* a = FirstAttribute();
  1540. const XMLAttribute* b = other->FirstAttribute();
  1541. while (a && b) {
  1542. if (!XMLUtil::StringEqual(a->Value(), b->Value())) {
  1543. return false;
  1544. }
  1545. a = a->Next();
  1546. b = b->Next();
  1547. }
  1548. if (a || b) {
  1549. // different count
  1550. return false;
  1551. }
  1552. return true;
  1553. }
  1554. return false;
  1555. }
  1556. bool XMLElement::Accept(XMLVisitor* visitor) const
  1557. {
  1558. TIXMLASSERT(visitor);
  1559. if (visitor->VisitEnter(*this, _rootAttribute)) {
  1560. for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) {
  1561. if (!node->Accept(visitor)) {
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. return visitor->VisitExit(*this);
  1567. }
  1568. // --------- XMLDocument ----------- //
  1569. // Warning: List must match 'enum XMLError'
  1570. const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {"XML_SUCCESS",
  1571. "XML_NO_ATTRIBUTE",
  1572. "XML_WRONG_ATTRIBUTE_TYPE",
  1573. "XML_ERROR_FILE_NOT_FOUND",
  1574. "XML_ERROR_FILE_COULD_NOT_BE_OPENED",
  1575. "XML_ERROR_FILE_READ_ERROR",
  1576. "XML_ERROR_ELEMENT_MISMATCH",
  1577. "XML_ERROR_PARSING_ELEMENT",
  1578. "XML_ERROR_PARSING_ATTRIBUTE",
  1579. "XML_ERROR_IDENTIFYING_TAG",
  1580. "XML_ERROR_PARSING_TEXT",
  1581. "XML_ERROR_PARSING_CDATA",
  1582. "XML_ERROR_PARSING_COMMENT",
  1583. "XML_ERROR_PARSING_DECLARATION",
  1584. "XML_ERROR_PARSING_UNKNOWN",
  1585. "XML_ERROR_EMPTY_DOCUMENT",
  1586. "XML_ERROR_MISMATCHED_ELEMENT",
  1587. "XML_ERROR_PARSING",
  1588. "XML_CAN_NOT_CONVERT_TEXT",
  1589. "XML_NO_TEXT_NODE"};
  1590. XMLDocument::XMLDocument(bool processEntities, Whitespace whitespace)
  1591. : XMLNode(0)
  1592. , _writeBOM(false)
  1593. , _processEntities(processEntities)
  1594. , _errorID(XML_SUCCESS)
  1595. , _whitespace(whitespace)
  1596. , _charBuffer(0)
  1597. {
  1598. // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in
  1599. // VS2012+)
  1600. _document = this;
  1601. }
  1602. XMLDocument::~XMLDocument()
  1603. {
  1604. Clear();
  1605. }
  1606. void XMLDocument::Clear()
  1607. {
  1608. DeleteChildren();
  1609. #ifdef DEBUG
  1610. const bool hadError = Error();
  1611. #endif
  1612. ClearError();
  1613. delete[] _charBuffer;
  1614. _charBuffer = 0;
  1615. #if 0
  1616. _textPool.Trace( "text" );
  1617. _elementPool.Trace( "element" );
  1618. _commentPool.Trace( "comment" );
  1619. _attributePool.Trace( "attribute" );
  1620. #endif
  1621. #ifdef DEBUG
  1622. if (!hadError) {
  1623. TIXMLASSERT(_elementPool.CurrentAllocs() == _elementPool.Untracked());
  1624. TIXMLASSERT(_attributePool.CurrentAllocs() == _attributePool.Untracked());
  1625. TIXMLASSERT(_textPool.CurrentAllocs() == _textPool.Untracked());
  1626. TIXMLASSERT(_commentPool.CurrentAllocs() == _commentPool.Untracked());
  1627. }
  1628. #endif
  1629. }
  1630. XMLElement* XMLDocument::NewElement(const char* name)
  1631. {
  1632. TIXMLASSERT(sizeof(XMLElement) == _elementPool.ItemSize());
  1633. XMLElement* ele = new (_elementPool.Alloc()) XMLElement(this);
  1634. ele->_memPool = &_elementPool;
  1635. ele->SetName(name);
  1636. return ele;
  1637. }
  1638. XMLComment* XMLDocument::NewComment(const char* str)
  1639. {
  1640. TIXMLASSERT(sizeof(XMLComment) == _commentPool.ItemSize());
  1641. XMLComment* comment = new (_commentPool.Alloc()) XMLComment(this);
  1642. comment->_memPool = &_commentPool;
  1643. comment->SetValue(str);
  1644. return comment;
  1645. }
  1646. XMLText* XMLDocument::NewText(const char* str)
  1647. {
  1648. TIXMLASSERT(sizeof(XMLText) == _textPool.ItemSize());
  1649. XMLText* text = new (_textPool.Alloc()) XMLText(this);
  1650. text->_memPool = &_textPool;
  1651. text->SetValue(str);
  1652. return text;
  1653. }
  1654. XMLDeclaration* XMLDocument::NewDeclaration(const char* str)
  1655. {
  1656. TIXMLASSERT(sizeof(XMLDeclaration) == _commentPool.ItemSize());
  1657. XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration(this);
  1658. dec->_memPool = &_commentPool;
  1659. dec->SetValue(str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"");
  1660. return dec;
  1661. }
  1662. XMLUnknown* XMLDocument::NewUnknown(const char* str)
  1663. {
  1664. TIXMLASSERT(sizeof(XMLUnknown) == _commentPool.ItemSize());
  1665. XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown(this);
  1666. unk->_memPool = &_commentPool;
  1667. unk->SetValue(str);
  1668. return unk;
  1669. }
  1670. static FILE* callfopen(const char* filepath, const char* mode)
  1671. {
  1672. TIXMLASSERT(filepath);
  1673. TIXMLASSERT(mode);
  1674. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE)
  1675. FILE* fp = 0;
  1676. errno_t err = fopen_s(&fp, filepath, mode);
  1677. if (err) {
  1678. return 0;
  1679. }
  1680. #else
  1681. FILE* fp = fopen(filepath, mode);
  1682. #endif
  1683. return fp;
  1684. }
  1685. void XMLDocument::DeleteNode(XMLNode* node)
  1686. {
  1687. TIXMLASSERT(node);
  1688. TIXMLASSERT(node->_document == this);
  1689. if (node->_parent) {
  1690. node->_parent->DeleteChild(node);
  1691. } else {
  1692. // Isn't in the tree.
  1693. // Use the parent delete.
  1694. // Also, we need to mark it tracked: we 'know'
  1695. // it was never used.
  1696. node->_memPool->SetTracked();
  1697. // Call the static XMLNode version:
  1698. XMLNode::DeleteNode(node);
  1699. }
  1700. }
  1701. XMLError XMLDocument::LoadFile(const char* filename)
  1702. {
  1703. Clear();
  1704. FILE* fp = callfopen(filename, "rb");
  1705. if (!fp) {
  1706. SetError(XML_ERROR_FILE_NOT_FOUND, filename, 0);
  1707. return _errorID;
  1708. }
  1709. LoadFile(fp);
  1710. fclose(fp);
  1711. return _errorID;
  1712. }
  1713. // This is likely overengineered template art to have a check that unsigned long value incremented
  1714. // by one still fits into size_t. If size_t type is larger than unsigned long type
  1715. // (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit
  1716. // -Wtype-limits warning. This piece makes the compiler select code with a check when a check
  1717. // is useful and code with no check when a check is redundant depending on how size_t and unsigned
  1718. // long types sizes relate to each other.
  1719. template<bool = (sizeof(unsigned long) >= sizeof(size_t))>
  1720. struct LongFitsIntoSizeTMinusOne {
  1721. static bool Fits(unsigned long value)
  1722. {
  1723. return value < (size_t)-1;
  1724. }
  1725. };
  1726. template<>
  1727. struct LongFitsIntoSizeTMinusOne<false> {
  1728. static bool Fits(unsigned long)
  1729. {
  1730. return true;
  1731. }
  1732. };
  1733. XMLError XMLDocument::LoadFile(FILE* fp)
  1734. {
  1735. Clear();
  1736. fseek(fp, 0, SEEK_SET);
  1737. if (fgetc(fp) == EOF && ferror(fp) != 0) {
  1738. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  1739. return _errorID;
  1740. }
  1741. fseek(fp, 0, SEEK_END);
  1742. const long filelength = ftell(fp);
  1743. fseek(fp, 0, SEEK_SET);
  1744. if (filelength == -1L) {
  1745. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  1746. return _errorID;
  1747. }
  1748. TIXMLASSERT(filelength >= 0);
  1749. if (!LongFitsIntoSizeTMinusOne<>::Fits(filelength)) {
  1750. // Cannot handle files which won't fit in buffer together with null terminator
  1751. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  1752. return _errorID;
  1753. }
  1754. if (filelength == 0) {
  1755. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  1756. return _errorID;
  1757. }
  1758. const size_t size = filelength;
  1759. TIXMLASSERT(_charBuffer == 0);
  1760. _charBuffer = new char[size + 1];
  1761. size_t read = fread(_charBuffer, 1, size, fp);
  1762. if (read != size) {
  1763. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  1764. return _errorID;
  1765. }
  1766. _charBuffer[size] = 0;
  1767. Parse();
  1768. return _errorID;
  1769. }
  1770. XMLError XMLDocument::SaveFile(const char* filename, bool compact)
  1771. {
  1772. FILE* fp = callfopen(filename, "w");
  1773. if (!fp) {
  1774. SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0);
  1775. return _errorID;
  1776. }
  1777. SaveFile(fp, compact);
  1778. fclose(fp);
  1779. return _errorID;
  1780. }
  1781. XMLError XMLDocument::SaveFile(FILE* fp, bool compact)
  1782. {
  1783. // Clear any error from the last save, otherwise it will get reported
  1784. // for *this* call.
  1785. ClearError();
  1786. XMLPrinter stream(fp, compact);
  1787. Print(&stream);
  1788. return _errorID;
  1789. }
  1790. XMLError XMLDocument::Parse(const char* p, size_t len)
  1791. {
  1792. Clear();
  1793. if (len == 0 || !p || !*p) {
  1794. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  1795. return _errorID;
  1796. }
  1797. if (len == (size_t)(-1)) {
  1798. len = strlen(p);
  1799. }
  1800. TIXMLASSERT(_charBuffer == 0);
  1801. _charBuffer = new char[len + 1];
  1802. memcpy(_charBuffer, p, len);
  1803. _charBuffer[len] = 0;
  1804. Parse();
  1805. if (Error()) {
  1806. // clean up now essentially dangling memory.
  1807. // and the parse fail can put objects in the
  1808. // pools that are dead and inaccessible.
  1809. DeleteChildren();
  1810. _elementPool.Clear();
  1811. _attributePool.Clear();
  1812. _textPool.Clear();
  1813. _commentPool.Clear();
  1814. }
  1815. return _errorID;
  1816. }
  1817. void XMLDocument::Print(XMLPrinter* streamer) const
  1818. {
  1819. if (streamer) {
  1820. Accept(streamer);
  1821. } else {
  1822. XMLPrinter stdoutStreamer(stdout);
  1823. Accept(&stdoutStreamer);
  1824. }
  1825. }
  1826. void XMLDocument::SetError(XMLError error, const char* str1, const char* str2)
  1827. {
  1828. TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT);
  1829. _errorID = error;
  1830. _errorStr1.Reset();
  1831. _errorStr2.Reset();
  1832. if (str1)
  1833. _errorStr1.SetStr(str1);
  1834. if (str2)
  1835. _errorStr2.SetStr(str2);
  1836. }
  1837. const char* XMLDocument::ErrorName() const
  1838. {
  1839. TIXMLASSERT(_errorID >= 0 && _errorID < XML_ERROR_COUNT);
  1840. const char* errorName = _errorNames[_errorID];
  1841. TIXMLASSERT(errorName && errorName[0]);
  1842. return errorName;
  1843. }
  1844. void XMLDocument::PrintError() const
  1845. {
  1846. if (Error()) {
  1847. static const int LEN = 20;
  1848. char buf1[LEN] = {0};
  1849. char buf2[LEN] = {0};
  1850. if (!_errorStr1.Empty()) {
  1851. TIXML_SNPRINTF(buf1, LEN, "%s", _errorStr1.GetStr());
  1852. }
  1853. if (!_errorStr2.Empty()) {
  1854. TIXML_SNPRINTF(buf2, LEN, "%s", _errorStr2.GetStr());
  1855. }
  1856. // Should check INT_MIN <= _errorID && _errorId <= INT_MAX, but that
  1857. // causes a clang "always true" -Wtautological-constant-out-of-range-compare warning
  1858. TIXMLASSERT(0 <= _errorID && XML_ERROR_COUNT - 1 <= INT_MAX);
  1859. printf("XMLDocument error id=%d '%s' str1=%s str2=%s\n", static_cast<int>(_errorID),
  1860. ErrorName(), buf1, buf2);
  1861. }
  1862. }
  1863. void XMLDocument::Parse()
  1864. {
  1865. TIXMLASSERT(NoChildren()); // Clear() must have been called previously
  1866. TIXMLASSERT(_charBuffer);
  1867. char* p = _charBuffer;
  1868. p = XMLUtil::SkipWhiteSpace(p);
  1869. p = const_cast<char*>(XMLUtil::ReadBOM(p, &_writeBOM));
  1870. if (!*p) {
  1871. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  1872. return;
  1873. }
  1874. ParseDeep(p, 0);
  1875. }
  1876. XMLPrinter::XMLPrinter(FILE* file, bool compact, int depth)
  1877. : _elementJustOpened(false)
  1878. , _firstElement(true)
  1879. , _fp(file)
  1880. , _depth(depth)
  1881. , _textDepth(-1)
  1882. , _processEntities(true)
  1883. , _compactMode(compact)
  1884. {
  1885. for (int i = 0; i < ENTITY_RANGE; ++i) {
  1886. _entityFlag[i] = false;
  1887. _restrictedEntityFlag[i] = false;
  1888. }
  1889. for (int i = 0; i < NUM_ENTITIES; ++i) {
  1890. const char entityValue = entities[i].value;
  1891. TIXMLASSERT(((unsigned char)entityValue) < ENTITY_RANGE);
  1892. _entityFlag[(unsigned char)entityValue] = true;
  1893. }
  1894. _restrictedEntityFlag[(unsigned char)'&'] = true;
  1895. _restrictedEntityFlag[(unsigned char)'<'] = true;
  1896. _restrictedEntityFlag[(unsigned char)'>'] = true; // not required, but consistency is nice
  1897. _buffer.Push(0);
  1898. }
  1899. void XMLPrinter::Print(const char* format, ...)
  1900. {
  1901. va_list va;
  1902. va_start(va, format);
  1903. if (_fp) {
  1904. vfprintf(_fp, format, va);
  1905. } else {
  1906. const int len = TIXML_VSCPRINTF(format, va);
  1907. // Close out and re-start the va-args
  1908. va_end(va);
  1909. TIXMLASSERT(len >= 0);
  1910. va_start(va, format);
  1911. TIXMLASSERT(_buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0);
  1912. char* p = _buffer.PushArr(len) - 1; // back up over the null terminator.
  1913. TIXML_VSNPRINTF(p, len + 1, format, va);
  1914. }
  1915. va_end(va);
  1916. }
  1917. void XMLPrinter::PrintSpace(int depth)
  1918. {
  1919. for (int i = 0; i < depth; ++i) {
  1920. Print(" ");
  1921. }
  1922. }
  1923. void XMLPrinter::PrintString(const char* p, bool restricted)
  1924. {
  1925. // Look for runs of bytes between entities to print.
  1926. const char* q = p;
  1927. if (_processEntities) {
  1928. const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
  1929. while (*q) {
  1930. TIXMLASSERT(p <= q);
  1931. // Remember, char is sometimes signed. (How many times has that bitten me?)
  1932. if (*q > 0 && *q < ENTITY_RANGE) {
  1933. // Check for entities. If one is found, flush
  1934. // the stream up until the entity, write the
  1935. // entity, and keep looking.
  1936. if (flag[(unsigned char)(*q)]) {
  1937. while (p < q) {
  1938. const size_t delta = q - p;
  1939. // %.*s accepts type int as "precision"
  1940. const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta;
  1941. Print("%.*s", toPrint, p);
  1942. p += toPrint;
  1943. }
  1944. bool entityPatternPrinted = false;
  1945. for (int i = 0; i < NUM_ENTITIES; ++i) {
  1946. if (entities[i].value == *q) {
  1947. Print("&%s;", entities[i].pattern);
  1948. entityPatternPrinted = true;
  1949. break;
  1950. }
  1951. }
  1952. if (!entityPatternPrinted) {
  1953. // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable
  1954. // in release
  1955. TIXMLASSERT(false);
  1956. }
  1957. ++p;
  1958. }
  1959. }
  1960. ++q;
  1961. TIXMLASSERT(p <= q);
  1962. }
  1963. }
  1964. // Flush the remaining string. This will be the entire
  1965. // string if an entity wasn't found.
  1966. TIXMLASSERT(p <= q);
  1967. if (!_processEntities || (p < q)) {
  1968. Print("%s", p);
  1969. }
  1970. }
  1971. void XMLPrinter::PushHeader(bool writeBOM, bool writeDec)
  1972. {
  1973. if (writeBOM) {
  1974. static const unsigned char bom[] = {TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2,
  1975. 0};
  1976. Print("%s", bom);
  1977. }
  1978. if (writeDec) {
  1979. PushDeclaration("xml version=\"1.0\"");
  1980. }
  1981. }
  1982. void XMLPrinter::OpenElement(const char* name, bool compactMode)
  1983. {
  1984. SealElementIfJustOpened();
  1985. _stack.Push(name);
  1986. if (_textDepth < 0 && !_firstElement && !compactMode) {
  1987. Print("\n");
  1988. }
  1989. if (!compactMode) {
  1990. PrintSpace(_depth);
  1991. }
  1992. Print("<%s", name);
  1993. _elementJustOpened = true;
  1994. _firstElement = false;
  1995. ++_depth;
  1996. }
  1997. void XMLPrinter::PushAttribute(const char* name, const char* value)
  1998. {
  1999. TIXMLASSERT(_elementJustOpened);
  2000. Print(" %s=\"", name);
  2001. PrintString(value, false);
  2002. Print("\"");
  2003. }
  2004. void XMLPrinter::PushAttribute(const char* name, int v)
  2005. {
  2006. char buf[BUF_SIZE];
  2007. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2008. PushAttribute(name, buf);
  2009. }
  2010. void XMLPrinter::PushAttribute(const char* name, unsigned v)
  2011. {
  2012. char buf[BUF_SIZE];
  2013. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2014. PushAttribute(name, buf);
  2015. }
  2016. void XMLPrinter::PushAttribute(const char* name, int64_t v)
  2017. {
  2018. char buf[BUF_SIZE];
  2019. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2020. PushAttribute(name, buf);
  2021. }
  2022. void XMLPrinter::PushAttribute(const char* name, bool v)
  2023. {
  2024. char buf[BUF_SIZE];
  2025. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2026. PushAttribute(name, buf);
  2027. }
  2028. void XMLPrinter::PushAttribute(const char* name, double v)
  2029. {
  2030. char buf[BUF_SIZE];
  2031. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2032. PushAttribute(name, buf);
  2033. }
  2034. void XMLPrinter::CloseElement(bool compactMode)
  2035. {
  2036. --_depth;
  2037. const char* name = _stack.Pop();
  2038. if (_elementJustOpened) {
  2039. Print("/>");
  2040. } else {
  2041. if (_textDepth < 0 && !compactMode) {
  2042. Print("\n");
  2043. PrintSpace(_depth);
  2044. }
  2045. Print("</%s>", name);
  2046. }
  2047. if (_textDepth == _depth) {
  2048. _textDepth = -1;
  2049. }
  2050. if (_depth == 0 && !compactMode) {
  2051. Print("\n");
  2052. }
  2053. _elementJustOpened = false;
  2054. }
  2055. void XMLPrinter::SealElementIfJustOpened()
  2056. {
  2057. if (!_elementJustOpened) {
  2058. return;
  2059. }
  2060. _elementJustOpened = false;
  2061. Print(">");
  2062. }
  2063. void XMLPrinter::PushText(const char* text, bool cdata)
  2064. {
  2065. _textDepth = _depth - 1;
  2066. SealElementIfJustOpened();
  2067. if (cdata) {
  2068. Print("<![CDATA[%s]]>", text);
  2069. } else {
  2070. PrintString(text, true);
  2071. }
  2072. }
  2073. void XMLPrinter::PushText(int64_t value)
  2074. {
  2075. char buf[BUF_SIZE];
  2076. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2077. PushText(buf, false);
  2078. }
  2079. void XMLPrinter::PushText(int value)
  2080. {
  2081. char buf[BUF_SIZE];
  2082. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2083. PushText(buf, false);
  2084. }
  2085. void XMLPrinter::PushText(unsigned value)
  2086. {
  2087. char buf[BUF_SIZE];
  2088. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2089. PushText(buf, false);
  2090. }
  2091. void XMLPrinter::PushText(bool value)
  2092. {
  2093. char buf[BUF_SIZE];
  2094. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2095. PushText(buf, false);
  2096. }
  2097. void XMLPrinter::PushText(float value)
  2098. {
  2099. char buf[BUF_SIZE];
  2100. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2101. PushText(buf, false);
  2102. }
  2103. void XMLPrinter::PushText(double value)
  2104. {
  2105. char buf[BUF_SIZE];
  2106. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2107. PushText(buf, false);
  2108. }
  2109. void XMLPrinter::PushComment(const char* comment)
  2110. {
  2111. SealElementIfJustOpened();
  2112. if (_textDepth < 0 && !_firstElement && !_compactMode) {
  2113. Print("\n");
  2114. PrintSpace(_depth);
  2115. }
  2116. _firstElement = false;
  2117. Print("<!--%s-->", comment);
  2118. }
  2119. void XMLPrinter::PushDeclaration(const char* value)
  2120. {
  2121. SealElementIfJustOpened();
  2122. if (_textDepth < 0 && !_firstElement && !_compactMode) {
  2123. Print("\n");
  2124. PrintSpace(_depth);
  2125. }
  2126. _firstElement = false;
  2127. Print("<?%s?>", value);
  2128. }
  2129. void XMLPrinter::PushUnknown(const char* value)
  2130. {
  2131. SealElementIfJustOpened();
  2132. if (_textDepth < 0 && !_firstElement && !_compactMode) {
  2133. Print("\n");
  2134. PrintSpace(_depth);
  2135. }
  2136. _firstElement = false;
  2137. Print("<!%s>", value);
  2138. }
  2139. bool XMLPrinter::VisitEnter(const XMLDocument& doc)
  2140. {
  2141. _processEntities = doc.ProcessEntities();
  2142. if (doc.HasBOM()) {
  2143. PushHeader(true, false);
  2144. }
  2145. return true;
  2146. }
  2147. bool XMLPrinter::VisitEnter(const XMLElement& element, const XMLAttribute* attribute)
  2148. {
  2149. const XMLElement* parentElem = 0;
  2150. if (element.Parent()) {
  2151. parentElem = element.Parent()->ToElement();
  2152. }
  2153. const bool compactMode = parentElem ? CompactMode(*parentElem) : _compactMode;
  2154. OpenElement(element.Name(), compactMode);
  2155. while (attribute) {
  2156. PushAttribute(attribute->Name(), attribute->Value());
  2157. attribute = attribute->Next();
  2158. }
  2159. return true;
  2160. }
  2161. bool XMLPrinter::VisitExit(const XMLElement& element)
  2162. {
  2163. CloseElement(CompactMode(element));
  2164. return true;
  2165. }
  2166. bool XMLPrinter::Visit(const XMLText& text)
  2167. {
  2168. PushText(text.Value(), text.CData());
  2169. return true;
  2170. }
  2171. bool XMLPrinter::Visit(const XMLComment& comment)
  2172. {
  2173. PushComment(comment.Value());
  2174. return true;
  2175. }
  2176. bool XMLPrinter::Visit(const XMLDeclaration& declaration)
  2177. {
  2178. PushDeclaration(declaration.Value());
  2179. return true;
  2180. }
  2181. bool XMLPrinter::Visit(const XMLUnknown& unknown)
  2182. {
  2183. PushUnknown(unknown.Value());
  2184. return true;
  2185. }
  2186. } // namespace tinyxml2