tinyxml2.cpp 66 KB

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