tinyxml2.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #ifndef TINYXML2_INCLUDED
  2. #define TINYXML2_INCLUDED
  3. /*
  4. TODO
  5. - const and non-const versions of API
  6. X memory pool the class construction
  7. - attribute accessors
  8. - node navigation
  9. - handles
  10. - visit pattern - change streamer?
  11. - make constructors protected
  12. - hide copy constructor
  13. - hide = operator
  14. X UTF8 support: isAlpha, etc.
  15. */
  16. #include <limits.h>
  17. #include <ctype.h>
  18. #include <stdio.h>
  19. #include <memory.h>
  20. #if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__)
  21. #ifndef DEBUG
  22. #define DEBUG
  23. #endif
  24. #endif
  25. #if defined(DEBUG)
  26. #if defined(_MSC_VER)
  27. #define TIXMLASSERT( x ) if ( !(x)) { _asm { int 3 } } //if ( !(x)) WinDebugBreak()
  28. #elif defined (ANDROID_NDK)
  29. #include <android/log.h>
  30. #define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
  31. #else
  32. #include <assert.h>
  33. #define TIXMLASSERT assert
  34. #endif
  35. #else
  36. #define TIXMLASSERT( x ) {}
  37. #endif
  38. namespace tinyxml2
  39. {
  40. class XMLDocument;
  41. class XMLElement;
  42. class XMLAttribute;
  43. class XMLComment;
  44. class XMLNode;
  45. class XMLText;
  46. class XMLStreamer;
  47. class StrPair
  48. {
  49. public:
  50. enum {
  51. NEEDS_ENTITY_PROCESSING = 0x01,
  52. NEEDS_NEWLINE_NORMALIZATION = 0x02,
  53. TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  54. ATTRIBUTE_NAME = 0,
  55. ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  56. COMMENT = NEEDS_NEWLINE_NORMALIZATION,
  57. };
  58. StrPair() : flags( 0 ), start( 0 ), end( 0 ) {}
  59. void Set( char* start, char* end, int flags ) {
  60. this->start = start; this->end = end; this->flags = flags | NEEDS_FLUSH;
  61. }
  62. const char* GetStr();
  63. bool Empty() const { return start == end; }
  64. void SetInternedStr( const char* str ) { this->start = (char*) str; this->end = 0; this->flags = 0; }
  65. char* ParseText( char* in, const char* endTag, int strFlags );
  66. char* ParseName( char* in );
  67. private:
  68. enum {
  69. NEEDS_FLUSH = 0x100
  70. };
  71. // After parsing, if *end != 0, it can be set to zero.
  72. int flags;
  73. char* start;
  74. char* end;
  75. };
  76. template <class T, int INIT>
  77. class DynArray
  78. {
  79. public:
  80. DynArray< T, INIT >()
  81. {
  82. mem = pool;
  83. allocated = INIT;
  84. size = 0;
  85. }
  86. ~DynArray()
  87. {
  88. if ( mem != pool ) {
  89. delete mem;
  90. }
  91. }
  92. void Push( T t )
  93. {
  94. EnsureCapacity( size+1 );
  95. mem[size++] = t;
  96. }
  97. T* PushArr( int count )
  98. {
  99. EnsureCapacity( size+count );
  100. T* ret = &mem[size];
  101. size += count;
  102. return ret;
  103. }
  104. T Pop() {
  105. return mem[--size];
  106. }
  107. void PopArr( int count )
  108. {
  109. TIXMLASSERT( size >= count );
  110. size -= count;
  111. }
  112. bool Empty() const { return size == 0; }
  113. T& operator[](int i) { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  114. const T& operator[](int i) const { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  115. int Size() const { return size; }
  116. const T* Mem() const { return mem; }
  117. T* Mem() { return mem; }
  118. private:
  119. void EnsureCapacity( int cap ) {
  120. if ( cap > allocated ) {
  121. int newAllocated = cap * 2;
  122. T* newMem = new T[newAllocated];
  123. memcpy( newMem, mem, sizeof(T)*size ); // warning: not using constructors, only works for PODs
  124. if ( mem != pool ) delete [] mem;
  125. mem = newMem;
  126. allocated = newAllocated;
  127. }
  128. }
  129. T* mem;
  130. T pool[INIT];
  131. int allocated; // objects allocated
  132. int size; // number objects in use
  133. };
  134. class MemPool
  135. {
  136. public:
  137. MemPool() {}
  138. virtual ~MemPool() {}
  139. virtual int ItemSize() const = 0;
  140. virtual void* Alloc() = 0;
  141. virtual void Free( void* ) = 0;
  142. };
  143. template< int SIZE >
  144. class MemPoolT : public MemPool
  145. {
  146. public:
  147. MemPoolT() : root(0), currentAllocs(0), nAllocs(0), maxAllocs(0) {}
  148. ~MemPoolT() {
  149. // Delete the blocks.
  150. for( int i=0; i<blockPtrs.Size(); ++i ) {
  151. delete blockPtrs[i];
  152. }
  153. }
  154. virtual int ItemSize() const { return SIZE; }
  155. int CurrentAllocs() const { return currentAllocs; }
  156. virtual void* Alloc() {
  157. if ( !root ) {
  158. // Need a new block.
  159. Block* block = new Block();
  160. blockPtrs.Push( block );
  161. for( int i=0; i<COUNT-1; ++i ) {
  162. block->chunk[i].next = &block->chunk[i+1];
  163. }
  164. block->chunk[COUNT-1].next = 0;
  165. root = block->chunk;
  166. }
  167. void* result = root;
  168. root = root->next;
  169. ++currentAllocs;
  170. if ( currentAllocs > maxAllocs ) maxAllocs = currentAllocs;
  171. nAllocs++;
  172. return result;
  173. }
  174. virtual void Free( void* mem ) {
  175. if ( !mem ) return;
  176. --currentAllocs;
  177. Chunk* chunk = (Chunk*)mem;
  178. memset( chunk, 0xfe, sizeof(Chunk) );
  179. chunk->next = root;
  180. root = chunk;
  181. }
  182. void Trace( const char* name ) {
  183. printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
  184. name, maxAllocs, maxAllocs*SIZE/1024, currentAllocs, SIZE, nAllocs, blockPtrs.Size() );
  185. }
  186. private:
  187. enum { COUNT = 1024/SIZE };
  188. union Chunk {
  189. Chunk* next;
  190. char mem[SIZE];
  191. };
  192. struct Block {
  193. Chunk chunk[COUNT];
  194. };
  195. DynArray< Block*, 10 > blockPtrs;
  196. Chunk* root;
  197. int currentAllocs;
  198. int nAllocs;
  199. int maxAllocs;
  200. };
  201. /*
  202. class StringStack
  203. {
  204. public:
  205. StringStack();
  206. virtual ~StringStack();
  207. void Push( const char* str );
  208. const char* Pop();
  209. int NumPositive() const { return nPositive; }
  210. private:
  211. DynArray< char, 50 > mem;
  212. int nPositive; // number of strings with len > 0
  213. };
  214. */
  215. /*
  216. class StringPool
  217. {
  218. public:
  219. enum { INIT_SIZE=20 };
  220. StringPool() : size( 0 ) {
  221. const char** mem = pool.PushArr( INIT_SIZE );
  222. memset( (void*)mem, 0, sizeof(char)*INIT_SIZE );
  223. }
  224. ~StringPool() {}
  225. const char* Intern( const char* str );
  226. private:
  227. // FNV hash
  228. int Hash( const char* s ) {
  229. #define FNV_32_PRIME ((int)0x01000193)
  230. int hval = 0;
  231. while (*s) {
  232. hval *= FNV_32_PRIME;
  233. hval ^= (int)*s++;
  234. }
  235. return hval;
  236. }
  237. int size;
  238. DynArray< const char*, INIT_SIZE > pool; // the hash table
  239. StringStack store; // memory for the interned strings
  240. };
  241. */
  242. /**
  243. Implements the interface to the "Visitor pattern" (see the Accept() method.)
  244. If you call the Accept() method, it requires being passed a XMLVisitor
  245. class to handle callbacks. For nodes that contain other nodes (Document, Element)
  246. you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves
  247. are simply called with Visit().
  248. If you return 'true' from a Visit method, recursive parsing will continue. If you return
  249. false, <b>no children of this node or its sibilings</b> will be Visited.
  250. All flavors of Visit methods have a default implementation that returns 'true' (continue
  251. visiting). You need to only override methods that are interesting to you.
  252. Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting.
  253. You should never change the document from a callback.
  254. @sa XMLNode::Accept()
  255. */
  256. class XMLVisitor
  257. {
  258. public:
  259. virtual ~XMLVisitor() {}
  260. /// Visit a document.
  261. virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { return true; }
  262. /// Visit a document.
  263. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; }
  264. /// Visit an element.
  265. virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { return true; }
  266. /// Visit an element.
  267. virtual bool VisitExit( const XMLElement& /*element*/ ) { return true; }
  268. /// Visit a declaration
  269. //virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; }
  270. /// Visit a text node
  271. virtual bool Visit( const XMLText& /*text*/ ) { return true; }
  272. /// Visit a comment node
  273. virtual bool Visit( const XMLComment& /*comment*/ ) { return true; }
  274. /// Visit an unknown node
  275. //virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; }
  276. };
  277. class XMLUtil
  278. {
  279. public:
  280. // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
  281. // correct, but simple, and usually works.
  282. static const char* SkipWhiteSpace( const char* p ) { while( IsUTF8Continuation(*p) || isspace( *p ) ) { ++p; } return p; }
  283. static char* SkipWhiteSpace( char* p ) { while( IsUTF8Continuation(*p) || isspace( *p ) ) { ++p; } return p; }
  284. inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
  285. int n = 0;
  286. if ( p == q ) {
  287. return true;
  288. }
  289. while( *p && *q && *p == *q && n<nChar ) {
  290. ++p; ++q; ++n;
  291. }
  292. if ( (n == nChar) || ( *p == 0 && *q == 0 ) ) {
  293. return true;
  294. }
  295. return false;
  296. }
  297. inline static int IsUTF8Continuation( unsigned char p ) { return p & 0x80; }
  298. inline static int IsAlphaNum( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalnum( anyByte ) : 1; }
  299. inline static int IsAlpha( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalpha( anyByte ) : 1; }
  300. };
  301. class XMLNode
  302. {
  303. friend class XMLDocument;
  304. friend class XMLElement;
  305. public:
  306. XMLDocument* GetDocument() { return document; }
  307. virtual XMLElement* ToElement() { return 0; }
  308. virtual XMLText* ToText() { return 0; }
  309. virtual XMLComment* ToComment() { return 0; }
  310. virtual XMLDocument* ToDocument() { return 0; }
  311. const char* Value() const { return value.GetStr(); }
  312. void SetValue( const char* val ) { value.SetInternedStr( val ); }
  313. const XMLNode* FirstChild() const { return firstChild; }
  314. XMLNode* FirstChild() { return firstChild; }
  315. const XMLElement* FirstChildElement( const char* value=0 ) const;
  316. XMLElement* FirstChildElement( const char* value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( value )); }
  317. const XMLNode* LastChild() const { return lastChild; }
  318. XMLNode* LastChild() { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->LastChild() ); }
  319. const XMLElement* LastChildElement( const char* value=0 ) const;
  320. XMLElement* LastChildElement( const char* value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(value) ); }
  321. const XMLNode* PreviousSibling() const { return prev; }
  322. XMLNode* PreviousSibling() { return prev; }
  323. const XMLNode* PreviousSiblingElement( const char* value=0 ) const ;
  324. XMLNode* PreviousSiblingElement( const char* value=0 ) { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( value ) ); }
  325. const XMLNode* NextSibling() const { return next; }
  326. XMLNode* NextSibling() { return next; }
  327. const XMLNode* NextSiblingElement( const char* value=0 ) const;
  328. XMLNode* NextSiblingElement( const char* value=0 ) { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->NextSiblingElement( value ) ); }
  329. XMLNode* InsertEndChild( XMLNode* addThis );
  330. XMLNode* InsertFirstChild( XMLNode* addThis );
  331. XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
  332. void ClearChildren();
  333. void DeleteChild( XMLNode* node );
  334. virtual bool Accept( XMLVisitor* visitor ) const = 0;
  335. virtual void Print( XMLStreamer* streamer );
  336. virtual char* ParseDeep( char* );
  337. void SetTextParent() { isTextParent = true; }
  338. bool IsTextParent() const { return isTextParent; }
  339. virtual bool IsClosingElement() const { return false; }
  340. protected:
  341. XMLNode( XMLDocument* );
  342. virtual ~XMLNode();
  343. XMLDocument* document;
  344. XMLNode* parent;
  345. bool isTextParent;
  346. mutable StrPair value;
  347. XMLNode* firstChild;
  348. XMLNode* lastChild;
  349. XMLNode* prev;
  350. XMLNode* next;
  351. private:
  352. MemPool* memPool;
  353. void Unlink( XMLNode* child );
  354. };
  355. class XMLText : public XMLNode
  356. {
  357. friend class XMLBase;
  358. friend class XMLDocument;
  359. public:
  360. virtual void Print( XMLStreamer* streamer );
  361. const char* Value() { return value.GetStr(); }
  362. void SetValue( const char* );
  363. virtual bool Accept( XMLVisitor* visitor ) const;
  364. virtual XMLText* ToText() { return this; }
  365. char* ParseDeep( char* );
  366. protected:
  367. XMLText( XMLDocument* doc ) : XMLNode( doc ) {}
  368. virtual ~XMLText() {}
  369. private:
  370. };
  371. class XMLComment : public XMLNode
  372. {
  373. friend class XMLBase;
  374. friend class XMLDocument;
  375. public:
  376. virtual void Print( XMLStreamer* );
  377. virtual XMLComment* ToComment() { return this; }
  378. const char* Value() { return value.GetStr(); }
  379. virtual bool Accept( XMLVisitor* visitor ) const;
  380. char* ParseDeep( char* );
  381. protected:
  382. XMLComment( XMLDocument* doc );
  383. virtual ~XMLComment();
  384. private:
  385. };
  386. class XMLAttribute
  387. {
  388. friend class XMLElement;
  389. public:
  390. virtual void Print( XMLStreamer* streamer );
  391. private:
  392. XMLAttribute( XMLElement* element ) : next( 0 ) {}
  393. virtual ~XMLAttribute() {}
  394. char* ParseDeep( char* p );
  395. StrPair name;
  396. StrPair value;
  397. XMLAttribute* next;
  398. MemPool* memPool;
  399. };
  400. class XMLElement : public XMLNode
  401. {
  402. friend class XMLBase;
  403. friend class XMLDocument;
  404. public:
  405. const char* Name() const { return Value(); }
  406. void SetName( const char* str ) { SetValue( str ); }
  407. virtual void Print( XMLStreamer* );
  408. virtual XMLElement* ToElement() { return this; }
  409. virtual bool Accept( XMLVisitor* visitor ) const;
  410. // internal:
  411. virtual bool IsClosingElement() const { return closing; }
  412. char* ParseDeep( char* p );
  413. protected:
  414. XMLElement( XMLDocument* doc );
  415. virtual ~XMLElement();
  416. private:
  417. char* ParseAttributes( char* p, bool *closedElement );
  418. bool closing;
  419. XMLAttribute* rootAttribute;
  420. XMLAttribute* lastAttribute;
  421. };
  422. class XMLDocument : public XMLNode
  423. {
  424. friend class XMLElement;
  425. public:
  426. XMLDocument();
  427. ~XMLDocument();
  428. virtual XMLDocument* ToDocument() { return this; }
  429. int Parse( const char* );
  430. int Load( const char* );
  431. int Load( FILE* );
  432. void Print( XMLStreamer* streamer=0 );
  433. virtual bool Accept( XMLVisitor* visitor ) const;
  434. XMLElement* NewElement( const char* name );
  435. enum {
  436. NO_ERROR = 0,
  437. ERROR_ELEMENT_MISMATCH,
  438. ERROR_PARSING_ELEMENT,
  439. ERROR_PARSING_ATTRIBUTE
  440. };
  441. void SetError( int error, const char* str1, const char* str2 );
  442. bool Error() const { return errorID != NO_ERROR; }
  443. int GetErrorID() const { return errorID; }
  444. const char* GetErrorStr1() const { return errorStr1; }
  445. const char* GetErrorStr2() const { return errorStr2; }
  446. char* Identify( char* p, XMLNode** node );
  447. private:
  448. XMLDocument( const XMLDocument& ); // intentionally not implemented
  449. void InitDocument();
  450. int errorID;
  451. const char* errorStr1;
  452. const char* errorStr2;
  453. char* charBuffer;
  454. //StringStack stringPool;
  455. MemPoolT< sizeof(XMLElement) > elementPool;
  456. MemPoolT< sizeof(XMLAttribute) > attributePool;
  457. MemPoolT< sizeof(XMLText) > textPool;
  458. MemPoolT< sizeof(XMLComment) > commentPool;
  459. };
  460. class XMLStreamer
  461. {
  462. public:
  463. XMLStreamer( FILE* file );
  464. ~XMLStreamer() {}
  465. void OpenElement( const char* name );
  466. void PushAttribute( const char* name, const char* value );
  467. void CloseElement();
  468. void PushText( const char* text );
  469. void PushComment( const char* comment );
  470. private:
  471. void SealElement();
  472. void PrintSpace( int depth );
  473. void PrintString( const char* ); // prints out, after detecting entities.
  474. /* bool TextOnStack() const {
  475. for( int i=0; i<text.Size(); ++i ) {
  476. if ( text[i] == 'T' )
  477. return true;
  478. }
  479. return false;
  480. }*/
  481. FILE* fp;
  482. int depth;
  483. bool elementJustOpened;
  484. int textDepth;
  485. enum {
  486. ENTITY_RANGE = 64
  487. };
  488. bool entityFlag[ENTITY_RANGE];
  489. DynArray< const char*, 10 > stack;
  490. //DynArray< char, 10 > text;
  491. };
  492. }; // tinyxml2
  493. #endif // TINYXML2_INCLUDED