tinyxml2.cpp 63 KB

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