tinyxml2.cpp 65 KB

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