tinyxml2.cpp 67 KB

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