--- /dev/null
+/**\r
+ * pugixml parser - version 1.4\r
+ * --------------------------------------------------------\r
+ * Report bugs and download new versions at http://pugixml.org/\r
+ *\r
+ * This library is distributed under the MIT License. See notice at the end\r
+ * of this file.\r
+ *\r
+ * This work is based on the pugxml parser, which is:\r
+ */\r
+\r
+#ifndef SOURCE_PUGIXML_CPP\r
+#define SOURCE_PUGIXML_CPP\r
+\r
+#include "pugixml.hpp"\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+\r
+#ifdef PUGIXML_WCHAR_MODE\r
+# include <wchar.h>\r
+#endif\r
+\r
+#ifndef PUGIXML_NO_XPATH\r
+# include <math.h>\r
+# include <float.h>\r
+# ifdef PUGIXML_NO_EXCEPTIONS\r
+# include <setjmp.h>\r
+# endif\r
+#endif\r
+\r
+#ifndef PUGIXML_NO_STL\r
+# include <istream>\r
+# include <ostream>\r
+# include <string>\r
+#endif\r
+\r
+// For placement new\r
+#include <new>\r
+\r
+#ifdef _MSC_VER\r
+# pragma warning(push)\r
+# pragma warning(disable: 4127) // conditional expression is constant\r
+# pragma warning(disable: 4324) // structure was padded due to __declspec(align())\r
+# pragma warning(disable: 4611) // interaction between '_setjmp' and C++ object destruction is non-portable\r
+# pragma warning(disable: 4702) // unreachable code\r
+# pragma warning(disable: 4996) // this function or variable may be unsafe\r
+# pragma warning(disable: 4793) // function compiled as native: presence of '_setjmp' makes a function unmanaged\r
+#endif\r
+\r
+#ifdef __INTEL_COMPILER\r
+# pragma warning(disable: 177) // function was declared but never referenced \r
+# pragma warning(disable: 279) // controlling expression is constant\r
+# pragma warning(disable: 1478 1786) // function was declared "deprecated"\r
+# pragma warning(disable: 1684) // conversion from pointer to same-sized integral type\r
+#endif\r
+\r
+#if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY)\r
+# pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away\r
+#endif\r
+\r
+#ifdef __BORLANDC__\r
+# pragma option push\r
+# pragma warn -8008 // condition is always false\r
+# pragma warn -8066 // unreachable code\r
+#endif\r
+\r
+#ifdef __SNC__\r
+// Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug\r
+# pragma diag_suppress=178 // function was declared but never referenced\r
+# pragma diag_suppress=237 // controlling expression is constant\r
+#endif\r
+\r
+// Inlining controls\r
+#if defined(_MSC_VER) && _MSC_VER >= 1300\r
+# define PUGI__NO_INLINE __declspec(noinline)\r
+#elif defined(__GNUC__)\r
+# define PUGI__NO_INLINE __attribute__((noinline))\r
+#else\r
+# define PUGI__NO_INLINE \r
+#endif\r
+\r
+// Simple static assertion\r
+#define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; }\r
+\r
+// Digital Mars C++ bug workaround for passing char loaded from memory via stack\r
+#ifdef __DMC__\r
+# define PUGI__DMC_VOLATILE volatile\r
+#else\r
+# define PUGI__DMC_VOLATILE\r
+#endif\r
+\r
+// Borland C++ bug workaround for not defining ::memcpy depending on header include order (can't always use std::memcpy because some compilers don't have it at all)\r
+#if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST)\r
+using std::memcpy;\r
+using std::memmove;\r
+#endif\r
+\r
+// In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features\r
+#if defined(_MSC_VER) && !defined(__S3E__)\r
+# define PUGI__MSVC_CRT_VERSION _MSC_VER\r
+#endif\r
+\r
+#ifdef PUGIXML_HEADER_ONLY\r
+# define PUGI__NS_BEGIN namespace pugi { namespace impl {\r
+# define PUGI__NS_END } }\r
+# define PUGI__FN inline\r
+# define PUGI__FN_NO_INLINE inline\r
+#else\r
+# if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces\r
+# define PUGI__NS_BEGIN namespace pugi { namespace impl {\r
+# define PUGI__NS_END } }\r
+# else\r
+# define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace {\r
+# define PUGI__NS_END } } }\r
+# endif\r
+# define PUGI__FN\r
+# define PUGI__FN_NO_INLINE PUGI__NO_INLINE\r
+#endif\r
+\r
+// uintptr_t\r
+#if !defined(_MSC_VER) || _MSC_VER >= 1600\r
+# include <stdint.h>\r
+#else\r
+# ifndef _UINTPTR_T_DEFINED\r
+// No native uintptr_t in MSVC6 and in some WinCE versions\r
+typedef size_t uintptr_t;\r
+#define _UINTPTR_T_DEFINED\r
+# endif\r
+PUGI__NS_BEGIN\r
+ typedef unsigned __int8 uint8_t;\r
+ typedef unsigned __int16 uint16_t;\r
+ typedef unsigned __int32 uint32_t;\r
+PUGI__NS_END\r
+#endif\r
+\r
+// Memory allocation\r
+PUGI__NS_BEGIN\r
+ PUGI__FN void* default_allocate(size_t size)\r
+ {\r
+ return malloc(size);\r
+ }\r
+\r
+ PUGI__FN void default_deallocate(void* ptr)\r
+ {\r
+ free(ptr);\r
+ }\r
+\r
+ template <typename T>\r
+ struct xml_memory_management_function_storage\r
+ {\r
+ static allocation_function allocate;\r
+ static deallocation_function deallocate;\r
+ };\r
+\r
+ template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate;\r
+ template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate;\r
+\r
+ typedef xml_memory_management_function_storage<int> xml_memory;\r
+PUGI__NS_END\r
+\r
+// String utilities\r
+PUGI__NS_BEGIN\r
+ // Get string length\r
+ PUGI__FN size_t strlength(const char_t* s)\r
+ {\r
+ assert(s);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcslen(s);\r
+ #else\r
+ return strlen(s);\r
+ #endif\r
+ }\r
+\r
+ // Compare two strings\r
+ PUGI__FN bool strequal(const char_t* src, const char_t* dst)\r
+ {\r
+ assert(src && dst);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcscmp(src, dst) == 0;\r
+ #else\r
+ return strcmp(src, dst) == 0;\r
+ #endif\r
+ }\r
+\r
+ // Compare lhs with [rhs_begin, rhs_end)\r
+ PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count)\r
+ {\r
+ for (size_t i = 0; i < count; ++i)\r
+ if (lhs[i] != rhs[i])\r
+ return false;\r
+ \r
+ return lhs[count] == 0;\r
+ }\r
+\r
+ // Get length of wide string, even if CRT lacks wide character support\r
+ PUGI__FN size_t strlength_wide(const wchar_t* s)\r
+ {\r
+ assert(s);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcslen(s);\r
+ #else\r
+ const wchar_t* end = s;\r
+ while (*end) end++;\r
+ return static_cast<size_t>(end - s);\r
+ #endif\r
+ }\r
+\r
+#ifdef PUGIXML_WCHAR_MODE\r
+ // Convert string to wide string, assuming all symbols are ASCII\r
+ PUGI__FN void widen_ascii(wchar_t* dest, const char* source)\r
+ {\r
+ for (const char* i = source; *i; ++i) *dest++ = *i;\r
+ *dest = 0;\r
+ }\r
+#endif\r
+PUGI__NS_END\r
+\r
+#if !defined(PUGIXML_NO_STL) || !defined(PUGIXML_NO_XPATH)\r
+// auto_ptr-like buffer holder for exception recovery\r
+PUGI__NS_BEGIN\r
+ struct buffer_holder\r
+ {\r
+ void* data;\r
+ void (*deleter)(void*);\r
+\r
+ buffer_holder(void* data_, void (*deleter_)(void*)): data(data_), deleter(deleter_)\r
+ {\r
+ }\r
+\r
+ ~buffer_holder()\r
+ {\r
+ if (data) deleter(data);\r
+ }\r
+\r
+ void* release()\r
+ {\r
+ void* result = data;\r
+ data = 0;\r
+ return result;\r
+ }\r
+ };\r
+PUGI__NS_END\r
+#endif\r
+\r
+PUGI__NS_BEGIN\r
+ static const size_t xml_memory_page_size =\r
+ #ifdef PUGIXML_MEMORY_PAGE_SIZE\r
+ PUGIXML_MEMORY_PAGE_SIZE\r
+ #else\r
+ 32768\r
+ #endif\r
+ ;\r
+\r
+ static const uintptr_t xml_memory_page_alignment = 32;\r
+ static const uintptr_t xml_memory_page_pointer_mask = ~(xml_memory_page_alignment - 1);\r
+ static const uintptr_t xml_memory_page_name_allocated_mask = 16;\r
+ static const uintptr_t xml_memory_page_value_allocated_mask = 8;\r
+ static const uintptr_t xml_memory_page_type_mask = 7;\r
+\r
+ struct xml_allocator;\r
+\r
+ struct xml_memory_page\r
+ {\r
+ static xml_memory_page* construct(void* memory)\r
+ {\r
+ if (!memory) return 0; //$ redundant, left for performance\r
+\r
+ xml_memory_page* result = static_cast<xml_memory_page*>(memory);\r
+\r
+ result->allocator = 0;\r
+ result->memory = 0;\r
+ result->prev = 0;\r
+ result->next = 0;\r
+ result->busy_size = 0;\r
+ result->freed_size = 0;\r
+\r
+ return result;\r
+ }\r
+\r
+ xml_allocator* allocator;\r
+\r
+ void* memory;\r
+\r
+ xml_memory_page* prev;\r
+ xml_memory_page* next;\r
+\r
+ size_t busy_size;\r
+ size_t freed_size;\r
+\r
+ char data[1];\r
+ };\r
+\r
+ struct xml_memory_string_header\r
+ {\r
+ uint16_t page_offset; // offset from page->data\r
+ uint16_t full_size; // 0 if string occupies whole page\r
+ };\r
+\r
+ struct xml_allocator\r
+ {\r
+ xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size)\r
+ {\r
+ }\r
+\r
+ xml_memory_page* allocate_page(size_t data_size)\r
+ {\r
+ size_t size = offsetof(xml_memory_page, data) + data_size;\r
+\r
+ // allocate block with some alignment, leaving memory for worst-case padding\r
+ void* memory = xml_memory::allocate(size + xml_memory_page_alignment);\r
+ if (!memory) return 0;\r
+\r
+ // align upwards to page boundary\r
+ void* page_memory = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(memory) + (xml_memory_page_alignment - 1)) & ~(xml_memory_page_alignment - 1));\r
+\r
+ // prepare page structure\r
+ xml_memory_page* page = xml_memory_page::construct(page_memory);\r
+ assert(page);\r
+\r
+ page->memory = memory;\r
+ page->allocator = _root->allocator;\r
+\r
+ return page;\r
+ }\r
+\r
+ static void deallocate_page(xml_memory_page* page)\r
+ {\r
+ xml_memory::deallocate(page->memory);\r
+ }\r
+\r
+ void* allocate_memory_oob(size_t size, xml_memory_page*& out_page);\r
+\r
+ void* allocate_memory(size_t size, xml_memory_page*& out_page)\r
+ {\r
+ if (_busy_size + size > xml_memory_page_size) return allocate_memory_oob(size, out_page);\r
+\r
+ void* buf = _root->data + _busy_size;\r
+\r
+ _busy_size += size;\r
+\r
+ out_page = _root;\r
+\r
+ return buf;\r
+ }\r
+\r
+ void deallocate_memory(void* ptr, size_t size, xml_memory_page* page)\r
+ {\r
+ if (page == _root) page->busy_size = _busy_size;\r
+\r
+ assert(ptr >= page->data && ptr < page->data + page->busy_size);\r
+ (void)!ptr;\r
+\r
+ page->freed_size += size;\r
+ assert(page->freed_size <= page->busy_size);\r
+\r
+ if (page->freed_size == page->busy_size)\r
+ {\r
+ if (page->next == 0)\r
+ {\r
+ assert(_root == page);\r
+\r
+ // top page freed, just reset sizes\r
+ page->busy_size = page->freed_size = 0;\r
+ _busy_size = 0;\r
+ }\r
+ else\r
+ {\r
+ assert(_root != page);\r
+ assert(page->prev);\r
+\r
+ // remove from the list\r
+ page->prev->next = page->next;\r
+ page->next->prev = page->prev;\r
+\r
+ // deallocate\r
+ deallocate_page(page);\r
+ }\r
+ }\r
+ }\r
+\r
+ char_t* allocate_string(size_t length)\r
+ {\r
+ // allocate memory for string and header block\r
+ size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t);\r
+ \r
+ // round size up to pointer alignment boundary\r
+ size_t full_size = (size + (sizeof(void*) - 1)) & ~(sizeof(void*) - 1);\r
+\r
+ xml_memory_page* page;\r
+ xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page));\r
+\r
+ if (!header) return 0;\r
+\r
+ // setup header\r
+ ptrdiff_t page_offset = reinterpret_cast<char*>(header) - page->data;\r
+\r
+ assert(page_offset >= 0 && page_offset < (1 << 16));\r
+ header->page_offset = static_cast<uint16_t>(page_offset);\r
+\r
+ // full_size == 0 for large strings that occupy the whole page\r
+ assert(full_size < (1 << 16) || (page->busy_size == full_size && page_offset == 0));\r
+ header->full_size = static_cast<uint16_t>(full_size < (1 << 16) ? full_size : 0);\r
+\r
+ // round-trip through void* to avoid 'cast increases required alignment of target type' warning\r
+ // header is guaranteed a pointer-sized alignment, which should be enough for char_t\r
+ return static_cast<char_t*>(static_cast<void*>(header + 1));\r
+ }\r
+\r
+ void deallocate_string(char_t* string)\r
+ {\r
+ // this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings\r
+ // we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string\r
+\r
+ // get header\r
+ xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1;\r
+\r
+ // deallocate\r
+ size_t page_offset = offsetof(xml_memory_page, data) + header->page_offset;\r
+ xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset));\r
+\r
+ // if full_size == 0 then this string occupies the whole page\r
+ size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size;\r
+\r
+ deallocate_memory(header, full_size, page);\r
+ }\r
+\r
+ xml_memory_page* _root;\r
+ size_t _busy_size;\r
+ };\r
+\r
+ PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page)\r
+ {\r
+ const size_t large_allocation_threshold = xml_memory_page_size / 4;\r
+\r
+ xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size);\r
+ out_page = page;\r
+\r
+ if (!page) return 0;\r
+\r
+ if (size <= large_allocation_threshold)\r
+ {\r
+ _root->busy_size = _busy_size;\r
+\r
+ // insert page at the end of linked list\r
+ page->prev = _root;\r
+ _root->next = page;\r
+ _root = page;\r
+\r
+ _busy_size = size;\r
+ }\r
+ else\r
+ {\r
+ // insert page before the end of linked list, so that it is deleted as soon as possible\r
+ // the last page is not deleted even if it's empty (see deallocate_memory)\r
+ assert(_root->prev);\r
+\r
+ page->prev = _root->prev;\r
+ page->next = _root;\r
+\r
+ _root->prev->next = page;\r
+ _root->prev = page;\r
+ }\r
+\r
+ // allocate inside page\r
+ page->busy_size = size;\r
+\r
+ return page->data;\r
+ }\r
+PUGI__NS_END\r
+\r
+namespace pugi\r
+{\r
+ /// A 'name=value' XML attribute structure.\r
+ struct xml_attribute_struct\r
+ {\r
+ /// Default ctor\r
+ xml_attribute_struct(impl::xml_memory_page* page): header(reinterpret_cast<uintptr_t>(page)), name(0), value(0), prev_attribute_c(0), next_attribute(0)\r
+ {\r
+ }\r
+\r
+ uintptr_t header;\r
+\r
+ char_t* name; ///< Pointer to attribute name.\r
+ char_t* value; ///< Pointer to attribute value.\r
+\r
+ xml_attribute_struct* prev_attribute_c; ///< Previous attribute (cyclic list)\r
+ xml_attribute_struct* next_attribute; ///< Next attribute\r
+ };\r
+\r
+ /// An XML document tree node.\r
+ struct xml_node_struct\r
+ {\r
+ /// Default ctor\r
+ /// \param type - node type\r
+ xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(reinterpret_cast<uintptr_t>(page) | (type - 1)), parent(0), name(0), value(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0)\r
+ {\r
+ }\r
+\r
+ uintptr_t header;\r
+\r
+ xml_node_struct* parent; ///< Pointer to parent\r
+\r
+ char_t* name; ///< Pointer to element name.\r
+ char_t* value; ///< Pointer to any associated string data.\r
+\r
+ xml_node_struct* first_child; ///< First child\r
+ \r
+ xml_node_struct* prev_sibling_c; ///< Left brother (cyclic list)\r
+ xml_node_struct* next_sibling; ///< Right brother\r
+ \r
+ xml_attribute_struct* first_attribute; ///< First attribute\r
+ };\r
+}\r
+\r
+PUGI__NS_BEGIN\r
+ struct xml_extra_buffer\r
+ {\r
+ char_t* buffer;\r
+ xml_extra_buffer* next;\r
+ };\r
+\r
+ struct xml_document_struct: public xml_node_struct, public xml_allocator\r
+ {\r
+ xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0), extra_buffers(0)\r
+ {\r
+ }\r
+\r
+ const char_t* buffer;\r
+\r
+ xml_extra_buffer* extra_buffers;\r
+ };\r
+\r
+ inline xml_allocator& get_allocator(const xml_node_struct* node)\r
+ {\r
+ assert(node);\r
+\r
+ return *reinterpret_cast<xml_memory_page*>(node->header & xml_memory_page_pointer_mask)->allocator;\r
+ }\r
+PUGI__NS_END\r
+\r
+// Low-level DOM operations\r
+PUGI__NS_BEGIN\r
+ inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc)\r
+ {\r
+ xml_memory_page* page;\r
+ void* memory = alloc.allocate_memory(sizeof(xml_attribute_struct), page);\r
+\r
+ return new (memory) xml_attribute_struct(page);\r
+ }\r
+\r
+ inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type)\r
+ {\r
+ xml_memory_page* page;\r
+ void* memory = alloc.allocate_memory(sizeof(xml_node_struct), page);\r
+\r
+ return new (memory) xml_node_struct(page, type);\r
+ }\r
+\r
+ inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc)\r
+ {\r
+ uintptr_t header = a->header;\r
+\r
+ if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(a->name);\r
+ if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(a->value);\r
+\r
+ alloc.deallocate_memory(a, sizeof(xml_attribute_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));\r
+ }\r
+\r
+ inline void destroy_node(xml_node_struct* n, xml_allocator& alloc)\r
+ {\r
+ uintptr_t header = n->header;\r
+\r
+ if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(n->name);\r
+ if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(n->value);\r
+\r
+ for (xml_attribute_struct* attr = n->first_attribute; attr; )\r
+ {\r
+ xml_attribute_struct* next = attr->next_attribute;\r
+\r
+ destroy_attribute(attr, alloc);\r
+\r
+ attr = next;\r
+ }\r
+\r
+ for (xml_node_struct* child = n->first_child; child; )\r
+ {\r
+ xml_node_struct* next = child->next_sibling;\r
+\r
+ destroy_node(child, alloc);\r
+\r
+ child = next;\r
+ }\r
+\r
+ alloc.deallocate_memory(n, sizeof(xml_node_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));\r
+ }\r
+\r
+ PUGI__FN_NO_INLINE xml_node_struct* append_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element)\r
+ {\r
+ xml_node_struct* child = allocate_node(alloc, type);\r
+ if (!child) return 0;\r
+\r
+ child->parent = node;\r
+\r
+ xml_node_struct* first_child = node->first_child;\r
+ \r
+ if (first_child)\r
+ {\r
+ xml_node_struct* last_child = first_child->prev_sibling_c;\r
+\r
+ last_child->next_sibling = child;\r
+ child->prev_sibling_c = last_child;\r
+ first_child->prev_sibling_c = child;\r
+ }\r
+ else\r
+ {\r
+ node->first_child = child;\r
+ child->prev_sibling_c = child;\r
+ }\r
+ \r
+ return child;\r
+ }\r
+\r
+ PUGI__FN_NO_INLINE xml_attribute_struct* append_attribute_ll(xml_node_struct* node, xml_allocator& alloc)\r
+ {\r
+ xml_attribute_struct* a = allocate_attribute(alloc);\r
+ if (!a) return 0;\r
+\r
+ xml_attribute_struct* first_attribute = node->first_attribute;\r
+\r
+ if (first_attribute)\r
+ {\r
+ xml_attribute_struct* last_attribute = first_attribute->prev_attribute_c;\r
+\r
+ last_attribute->next_attribute = a;\r
+ a->prev_attribute_c = last_attribute;\r
+ first_attribute->prev_attribute_c = a;\r
+ }\r
+ else\r
+ {\r
+ node->first_attribute = a;\r
+ a->prev_attribute_c = a;\r
+ }\r
+ \r
+ return a;\r
+ }\r
+PUGI__NS_END\r
+\r
+// Helper classes for code generation\r
+PUGI__NS_BEGIN\r
+ struct opt_false\r
+ {\r
+ enum { value = 0 };\r
+ };\r
+\r
+ struct opt_true\r
+ {\r
+ enum { value = 1 };\r
+ };\r
+PUGI__NS_END\r
+\r
+// Unicode utilities\r
+PUGI__NS_BEGIN\r
+ inline uint16_t endian_swap(uint16_t value)\r
+ {\r
+ return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8));\r
+ }\r
+\r
+ inline uint32_t endian_swap(uint32_t value)\r
+ {\r
+ return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24);\r
+ }\r
+\r
+ struct utf8_counter\r
+ {\r
+ typedef size_t value_type;\r
+\r
+ static value_type low(value_type result, uint32_t ch)\r
+ {\r
+ // U+0000..U+007F\r
+ if (ch < 0x80) return result + 1;\r
+ // U+0080..U+07FF\r
+ else if (ch < 0x800) return result + 2;\r
+ // U+0800..U+FFFF\r
+ else return result + 3;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t)\r
+ {\r
+ // U+10000..U+10FFFF\r
+ return result + 4;\r
+ }\r
+ };\r
+\r
+ struct utf8_writer\r
+ {\r
+ typedef uint8_t* value_type;\r
+\r
+ static value_type low(value_type result, uint32_t ch)\r
+ {\r
+ // U+0000..U+007F\r
+ if (ch < 0x80)\r
+ {\r
+ *result = static_cast<uint8_t>(ch);\r
+ return result + 1;\r
+ }\r
+ // U+0080..U+07FF\r
+ else if (ch < 0x800)\r
+ {\r
+ result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6));\r
+ result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F));\r
+ return result + 2;\r
+ }\r
+ // U+0800..U+FFFF\r
+ else\r
+ {\r
+ result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12));\r
+ result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));\r
+ result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F));\r
+ return result + 3;\r
+ }\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t ch)\r
+ {\r
+ // U+10000..U+10FFFF\r
+ result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18));\r
+ result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F));\r
+ result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));\r
+ result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F));\r
+ return result + 4;\r
+ }\r
+\r
+ static value_type any(value_type result, uint32_t ch)\r
+ {\r
+ return (ch < 0x10000) ? low(result, ch) : high(result, ch);\r
+ }\r
+ };\r
+\r
+ struct utf16_counter\r
+ {\r
+ typedef size_t value_type;\r
+\r
+ static value_type low(value_type result, uint32_t)\r
+ {\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t)\r
+ {\r
+ return result + 2;\r
+ }\r
+ };\r
+\r
+ struct utf16_writer\r
+ {\r
+ typedef uint16_t* value_type;\r
+\r
+ static value_type low(value_type result, uint32_t ch)\r
+ {\r
+ *result = static_cast<uint16_t>(ch);\r
+\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t ch)\r
+ {\r
+ uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10;\r
+ uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff;\r
+\r
+ result[0] = static_cast<uint16_t>(0xD800 + msh);\r
+ result[1] = static_cast<uint16_t>(0xDC00 + lsh);\r
+\r
+ return result + 2;\r
+ }\r
+\r
+ static value_type any(value_type result, uint32_t ch)\r
+ {\r
+ return (ch < 0x10000) ? low(result, ch) : high(result, ch);\r
+ }\r
+ };\r
+\r
+ struct utf32_counter\r
+ {\r
+ typedef size_t value_type;\r
+\r
+ static value_type low(value_type result, uint32_t)\r
+ {\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t)\r
+ {\r
+ return result + 1;\r
+ }\r
+ };\r
+\r
+ struct utf32_writer\r
+ {\r
+ typedef uint32_t* value_type;\r
+\r
+ static value_type low(value_type result, uint32_t ch)\r
+ {\r
+ *result = ch;\r
+\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t ch)\r
+ {\r
+ *result = ch;\r
+\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type any(value_type result, uint32_t ch)\r
+ {\r
+ *result = ch;\r
+\r
+ return result + 1;\r
+ }\r
+ };\r
+\r
+ struct latin1_writer\r
+ {\r
+ typedef uint8_t* value_type;\r
+\r
+ static value_type low(value_type result, uint32_t ch)\r
+ {\r
+ *result = static_cast<uint8_t>(ch > 255 ? '?' : ch);\r
+\r
+ return result + 1;\r
+ }\r
+\r
+ static value_type high(value_type result, uint32_t ch)\r
+ {\r
+ (void)ch;\r
+\r
+ *result = '?';\r
+\r
+ return result + 1;\r
+ }\r
+ };\r
+\r
+ template <size_t size> struct wchar_selector;\r
+\r
+ template <> struct wchar_selector<2>\r
+ {\r
+ typedef uint16_t type;\r
+ typedef utf16_counter counter;\r
+ typedef utf16_writer writer;\r
+ };\r
+\r
+ template <> struct wchar_selector<4>\r
+ {\r
+ typedef uint32_t type;\r
+ typedef utf32_counter counter;\r
+ typedef utf32_writer writer;\r
+ };\r
+\r
+ typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter;\r
+ typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer;\r
+\r
+ template <typename Traits, typename opt_swap = opt_false> struct utf_decoder\r
+ {\r
+ static inline typename Traits::value_type decode_utf8_block(const uint8_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ const uint8_t utf8_byte_mask = 0x3f;\r
+\r
+ while (size)\r
+ {\r
+ uint8_t lead = *data;\r
+\r
+ // 0xxxxxxx -> U+0000..U+007F\r
+ if (lead < 0x80)\r
+ {\r
+ result = Traits::low(result, lead);\r
+ data += 1;\r
+ size -= 1;\r
+\r
+ // process aligned single-byte (ascii) blocks\r
+ if ((reinterpret_cast<uintptr_t>(data) & 3) == 0)\r
+ {\r
+ // round-trip through void* to silence 'cast increases required alignment of target type' warnings\r
+ while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0)\r
+ {\r
+ result = Traits::low(result, data[0]);\r
+ result = Traits::low(result, data[1]);\r
+ result = Traits::low(result, data[2]);\r
+ result = Traits::low(result, data[3]);\r
+ data += 4;\r
+ size -= 4;\r
+ }\r
+ }\r
+ }\r
+ // 110xxxxx -> U+0080..U+07FF\r
+ else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80)\r
+ {\r
+ result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask));\r
+ data += 2;\r
+ size -= 2;\r
+ }\r
+ // 1110xxxx -> U+0800-U+FFFF\r
+ else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80)\r
+ {\r
+ result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask));\r
+ data += 3;\r
+ size -= 3;\r
+ }\r
+ // 11110xxx -> U+10000..U+10FFFF\r
+ else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80)\r
+ {\r
+ result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask));\r
+ data += 4;\r
+ size -= 4;\r
+ }\r
+ // 10xxxxxx or 11111xxx -> invalid\r
+ else\r
+ {\r
+ data += 1;\r
+ size -= 1;\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_utf16_block(const uint16_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ const uint16_t* end = data + size;\r
+\r
+ while (data < end)\r
+ {\r
+ unsigned int lead = opt_swap::value ? endian_swap(*data) : *data;\r
+\r
+ // U+0000..U+D7FF\r
+ if (lead < 0xD800)\r
+ {\r
+ result = Traits::low(result, lead);\r
+ data += 1;\r
+ }\r
+ // U+E000..U+FFFF\r
+ else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000)\r
+ {\r
+ result = Traits::low(result, lead);\r
+ data += 1;\r
+ }\r
+ // surrogate pair lead\r
+ else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && data + 1 < end)\r
+ {\r
+ uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1];\r
+\r
+ if (static_cast<unsigned int>(next - 0xDC00) < 0x400)\r
+ {\r
+ result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff));\r
+ data += 2;\r
+ }\r
+ else\r
+ {\r
+ data += 1;\r
+ }\r
+ }\r
+ else\r
+ {\r
+ data += 1;\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_utf32_block(const uint32_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ const uint32_t* end = data + size;\r
+\r
+ while (data < end)\r
+ {\r
+ uint32_t lead = opt_swap::value ? endian_swap(*data) : *data;\r
+\r
+ // U+0000..U+FFFF\r
+ if (lead < 0x10000)\r
+ {\r
+ result = Traits::low(result, lead);\r
+ data += 1;\r
+ }\r
+ // U+10000..U+10FFFF\r
+ else\r
+ {\r
+ result = Traits::high(result, lead);\r
+ data += 1;\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_latin1_block(const uint8_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ for (size_t i = 0; i < size; ++i)\r
+ {\r
+ result = Traits::low(result, data[i]);\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_wchar_block_impl(const uint16_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ return decode_utf16_block(data, size, result);\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_wchar_block_impl(const uint32_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ return decode_utf32_block(data, size, result);\r
+ }\r
+\r
+ static inline typename Traits::value_type decode_wchar_block(const wchar_t* data, size_t size, typename Traits::value_type result)\r
+ {\r
+ return decode_wchar_block_impl(reinterpret_cast<const wchar_selector<sizeof(wchar_t)>::type*>(data), size, result);\r
+ }\r
+ };\r
+\r
+ template <typename T> PUGI__FN void convert_utf_endian_swap(T* result, const T* data, size_t length)\r
+ {\r
+ for (size_t i = 0; i < length; ++i) result[i] = endian_swap(data[i]);\r
+ }\r
+\r
+#ifdef PUGIXML_WCHAR_MODE\r
+ PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length)\r
+ {\r
+ for (size_t i = 0; i < length; ++i) result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i])));\r
+ }\r
+#endif\r
+PUGI__NS_END\r
+\r
+PUGI__NS_BEGIN\r
+ enum chartype_t\r
+ {\r
+ ct_parse_pcdata = 1, // \0, &, \r, <\r
+ ct_parse_attr = 2, // \0, &, \r, ', "\r
+ ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab\r
+ ct_space = 8, // \r, \n, space, tab\r
+ ct_parse_cdata = 16, // \0, ], >, \r\r
+ ct_parse_comment = 32, // \0, -, >, \r\r
+ ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, .\r
+ ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, :\r
+ };\r
+\r
+ static const unsigned char chartype_table[256] =\r
+ {\r
+ 55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15\r
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31\r
+ 8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47\r
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63\r
+ 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95\r
+ 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127\r
+\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,\r
+ 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192\r
+ };\r
+\r
+ enum chartypex_t\r
+ {\r
+ ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, >\r
+ ctx_special_attr = 2, // Any symbol >= 0 and < 32 (except \t), &, <, >, "\r
+ ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _\r
+ ctx_digit = 8, // 0-9\r
+ ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, .\r
+ };\r
+ \r
+ static const unsigned char chartypex_table[256] =\r
+ {\r
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 2, 3, 3, 2, 3, 3, // 0-15\r
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31\r
+ 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47\r
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 3, 0, // 48-63\r
+\r
+ 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95\r
+ 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127\r
+\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\r
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20\r
+ };\r
+ \r
+#ifdef PUGIXML_WCHAR_MODE\r
+ #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct))\r
+#else\r
+ #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct))\r
+#endif\r
+\r
+ #define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table)\r
+ #define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table)\r
+\r
+ PUGI__FN bool is_little_endian()\r
+ {\r
+ unsigned int ui = 1;\r
+\r
+ return *reinterpret_cast<unsigned char*>(&ui) == 1;\r
+ }\r
+\r
+ PUGI__FN xml_encoding get_wchar_encoding()\r
+ {\r
+ PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4);\r
+\r
+ if (sizeof(wchar_t) == 2)\r
+ return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+ else \r
+ return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+ }\r
+\r
+ PUGI__FN xml_encoding guess_buffer_encoding(uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)\r
+ {\r
+ // look for BOM in first few bytes\r
+ if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be;\r
+ if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le;\r
+ if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be;\r
+ if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le;\r
+ if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8;\r
+\r
+ // look for <, <? or <?xm in various encodings\r
+ if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be;\r
+ if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le;\r
+ if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be;\r
+ if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le;\r
+ if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d) return encoding_utf8;\r
+\r
+ // look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early)\r
+ if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be;\r
+ if (d0 == 0x3c && d1 == 0) return encoding_utf16_le;\r
+\r
+ // no known BOM detected, assume utf8\r
+ return encoding_utf8;\r
+ }\r
+\r
+ PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size)\r
+ {\r
+ // replace wchar encoding with utf implementation\r
+ if (encoding == encoding_wchar) return get_wchar_encoding();\r
+\r
+ // replace utf16 encoding with utf16 with specific endianness\r
+ if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ // replace utf32 encoding with utf32 with specific endianness\r
+ if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ // only do autodetection if no explicit encoding is requested\r
+ if (encoding != encoding_auto) return encoding;\r
+\r
+ // skip encoding autodetection if input buffer is too small\r
+ if (size < 4) return encoding_utf8;\r
+\r
+ // try to guess encoding (based on XML specification, Appendix F.1)\r
+ const uint8_t* data = static_cast<const uint8_t*>(contents);\r
+\r
+ PUGI__DMC_VOLATILE uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3];\r
+\r
+ return guess_buffer_encoding(d0, d1, d2, d3);\r
+ }\r
+\r
+ PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)\r
+ {\r
+ size_t length = size / sizeof(char_t);\r
+\r
+ if (is_mutable)\r
+ {\r
+ out_buffer = static_cast<char_t*>(const_cast<void*>(contents));\r
+ out_length = length;\r
+ }\r
+ else\r
+ {\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ memcpy(buffer, contents, length * sizeof(char_t));\r
+ buffer[length] = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+ }\r
+\r
+ return true;\r
+ }\r
+\r
+#ifdef PUGIXML_WCHAR_MODE\r
+ PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re)\r
+ {\r
+ return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) ||\r
+ (le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be);\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)\r
+ {\r
+ const char_t* data = static_cast<const char_t*>(contents);\r
+ size_t length = size / sizeof(char_t);\r
+\r
+ if (is_mutable)\r
+ {\r
+ char_t* buffer = const_cast<char_t*>(data);\r
+\r
+ convert_wchar_endian_swap(buffer, data, length);\r
+\r
+ out_buffer = buffer;\r
+ out_length = length;\r
+ }\r
+ else\r
+ {\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ convert_wchar_endian_swap(buffer, data, length);\r
+ buffer[length] = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+ }\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer_utf8(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)\r
+ {\r
+ const uint8_t* data = static_cast<const uint8_t*>(contents);\r
+ size_t data_length = size;\r
+\r
+ // first pass: get length in wchar_t units\r
+ size_t length = utf_decoder<wchar_counter>::decode_utf8_block(data, data_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert utf8 input to wchar_t\r
+ wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);\r
+ wchar_writer::value_type oend = utf_decoder<wchar_writer>::decode_utf8_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)\r
+ {\r
+ const uint16_t* data = static_cast<const uint16_t*>(contents);\r
+ size_t data_length = size / sizeof(uint16_t);\r
+\r
+ // first pass: get length in wchar_t units\r
+ size_t length = utf_decoder<wchar_counter, opt_swap>::decode_utf16_block(data, data_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert utf16 input to wchar_t\r
+ wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);\r
+ wchar_writer::value_type oend = utf_decoder<wchar_writer, opt_swap>::decode_utf16_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)\r
+ {\r
+ const uint32_t* data = static_cast<const uint32_t*>(contents);\r
+ size_t data_length = size / sizeof(uint32_t);\r
+\r
+ // first pass: get length in wchar_t units\r
+ size_t length = utf_decoder<wchar_counter, opt_swap>::decode_utf32_block(data, data_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert utf32 input to wchar_t\r
+ wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);\r
+ wchar_writer::value_type oend = utf_decoder<wchar_writer, opt_swap>::decode_utf32_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)\r
+ {\r
+ const uint8_t* data = static_cast<const uint8_t*>(contents);\r
+ size_t data_length = size;\r
+\r
+ // get length in wchar_t units\r
+ size_t length = data_length;\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // convert latin1 input to wchar_t\r
+ wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);\r
+ wchar_writer::value_type oend = utf_decoder<wchar_writer>::decode_latin1_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)\r
+ {\r
+ // get native encoding\r
+ xml_encoding wchar_encoding = get_wchar_encoding();\r
+\r
+ // fast path: no conversion required\r
+ if (encoding == wchar_encoding) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);\r
+\r
+ // only endian-swapping is required\r
+ if (need_endian_swap_utf(encoding, wchar_encoding)) return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable);\r
+\r
+ // source encoding is utf8\r
+ if (encoding == encoding_utf8) return convert_buffer_utf8(out_buffer, out_length, contents, size);\r
+\r
+ // source encoding is utf16\r
+ if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)\r
+ {\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ return (native_encoding == encoding) ?\r
+ convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :\r
+ convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());\r
+ }\r
+\r
+ // source encoding is utf32\r
+ if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)\r
+ {\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ return (native_encoding == encoding) ?\r
+ convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :\r
+ convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());\r
+ }\r
+\r
+ // source encoding is latin1\r
+ if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size);\r
+\r
+ assert(!"Invalid encoding");\r
+ return false;\r
+ }\r
+#else\r
+ template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)\r
+ {\r
+ const uint16_t* data = static_cast<const uint16_t*>(contents);\r
+ size_t data_length = size / sizeof(uint16_t);\r
+\r
+ // first pass: get length in utf8 units\r
+ size_t length = utf_decoder<utf8_counter, opt_swap>::decode_utf16_block(data, data_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert utf16 input to utf8\r
+ uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);\r
+ uint8_t* oend = utf_decoder<utf8_writer, opt_swap>::decode_utf16_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)\r
+ {\r
+ const uint32_t* data = static_cast<const uint32_t*>(contents);\r
+ size_t data_length = size / sizeof(uint32_t);\r
+\r
+ // first pass: get length in utf8 units\r
+ size_t length = utf_decoder<utf8_counter, opt_swap>::decode_utf32_block(data, data_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert utf32 input to utf8\r
+ uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);\r
+ uint8_t* oend = utf_decoder<utf8_writer, opt_swap>::decode_utf32_block(data, data_length, obegin);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size)\r
+ {\r
+ for (size_t i = 0; i < size; ++i)\r
+ if (data[i] > 127)\r
+ return i;\r
+\r
+ return size;\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)\r
+ {\r
+ const uint8_t* data = static_cast<const uint8_t*>(contents);\r
+ size_t data_length = size;\r
+\r
+ // get size of prefix that does not need utf8 conversion\r
+ size_t prefix_length = get_latin1_7bit_prefix_length(data, data_length);\r
+ assert(prefix_length <= data_length);\r
+\r
+ const uint8_t* postfix = data + prefix_length;\r
+ size_t postfix_length = data_length - prefix_length;\r
+\r
+ // if no conversion is needed, just return the original buffer\r
+ if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);\r
+\r
+ // first pass: get length in utf8 units\r
+ size_t length = prefix_length + utf_decoder<utf8_counter>::decode_latin1_block(postfix, postfix_length, 0);\r
+\r
+ // allocate buffer of suitable length\r
+ char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!buffer) return false;\r
+\r
+ // second pass: convert latin1 input to utf8\r
+ memcpy(buffer, data, prefix_length);\r
+\r
+ uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);\r
+ uint8_t* oend = utf_decoder<utf8_writer>::decode_latin1_block(postfix, postfix_length, obegin + prefix_length);\r
+\r
+ assert(oend == obegin + length);\r
+ *oend = 0;\r
+\r
+ out_buffer = buffer;\r
+ out_length = length + 1;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)\r
+ {\r
+ // fast path: no conversion required\r
+ if (encoding == encoding_utf8) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);\r
+\r
+ // source encoding is utf16\r
+ if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)\r
+ {\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ return (native_encoding == encoding) ?\r
+ convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :\r
+ convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());\r
+ }\r
+\r
+ // source encoding is utf32\r
+ if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)\r
+ {\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ return (native_encoding == encoding) ?\r
+ convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :\r
+ convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());\r
+ }\r
+\r
+ // source encoding is latin1\r
+ if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable);\r
+\r
+ assert(!"Invalid encoding");\r
+ return false;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length)\r
+ {\r
+ // get length in utf8 characters\r
+ return utf_decoder<utf8_counter>::decode_wchar_block(str, length, 0);\r
+ }\r
+\r
+ PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length)\r
+ {\r
+ // convert to utf8\r
+ uint8_t* begin = reinterpret_cast<uint8_t*>(buffer);\r
+ uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(str, length, begin);\r
+ \r
+ assert(begin + size == end);\r
+ (void)!end;\r
+\r
+ // zero-terminate\r
+ buffer[size] = 0;\r
+ }\r
+ \r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length)\r
+ {\r
+ // first pass: get length in utf8 characters\r
+ size_t size = as_utf8_begin(str, length);\r
+\r
+ // allocate resulting string\r
+ std::string result;\r
+ result.resize(size);\r
+\r
+ // second pass: convert to utf8\r
+ if (size > 0) as_utf8_end(&result[0], size, str, length);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size)\r
+ {\r
+ const uint8_t* data = reinterpret_cast<const uint8_t*>(str);\r
+\r
+ // first pass: get length in wchar_t units\r
+ size_t length = utf_decoder<wchar_counter>::decode_utf8_block(data, size, 0);\r
+\r
+ // allocate resulting string\r
+ std::basic_string<wchar_t> result;\r
+ result.resize(length);\r
+\r
+ // second pass: convert to wchar_t\r
+ if (length > 0)\r
+ {\r
+ wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]);\r
+ wchar_writer::value_type end = utf_decoder<wchar_writer>::decode_utf8_block(data, size, begin);\r
+\r
+ assert(begin + length == end);\r
+ (void)!end;\r
+ }\r
+\r
+ return result;\r
+ }\r
+#endif\r
+\r
+ inline bool strcpy_insitu_allow(size_t length, uintptr_t allocated, char_t* target)\r
+ {\r
+ assert(target);\r
+ size_t target_length = strlength(target);\r
+\r
+ // always reuse document buffer memory if possible\r
+ if (!allocated) return target_length >= length;\r
+\r
+ // reuse heap memory if waste is not too great\r
+ const size_t reuse_threshold = 32;\r
+\r
+ return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2);\r
+ }\r
+\r
+ PUGI__FN bool strcpy_insitu(char_t*& dest, uintptr_t& header, uintptr_t header_mask, const char_t* source)\r
+ {\r
+ assert(header);\r
+\r
+ size_t source_length = strlength(source);\r
+\r
+ if (source_length == 0)\r
+ {\r
+ // empty string and null pointer are equivalent, so just deallocate old memory\r
+ xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;\r
+\r
+ if (header & header_mask) alloc->deallocate_string(dest);\r
+ \r
+ // mark the string as not allocated\r
+ dest = 0;\r
+ header &= ~header_mask;\r
+\r
+ return true;\r
+ }\r
+ else if (dest && strcpy_insitu_allow(source_length, header & header_mask, dest))\r
+ {\r
+ // we can reuse old buffer, so just copy the new data (including zero terminator)\r
+ memcpy(dest, source, (source_length + 1) * sizeof(char_t));\r
+ \r
+ return true;\r
+ }\r
+ else\r
+ {\r
+ xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;\r
+\r
+ // allocate new buffer\r
+ char_t* buf = alloc->allocate_string(source_length + 1);\r
+ if (!buf) return false;\r
+\r
+ // copy the string (including zero terminator)\r
+ memcpy(buf, source, (source_length + 1) * sizeof(char_t));\r
+\r
+ // deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures)\r
+ if (header & header_mask) alloc->deallocate_string(dest);\r
+ \r
+ // the string is now allocated, so set the flag\r
+ dest = buf;\r
+ header |= header_mask;\r
+\r
+ return true;\r
+ }\r
+ }\r
+\r
+ struct gap\r
+ {\r
+ char_t* end;\r
+ size_t size;\r
+ \r
+ gap(): end(0), size(0)\r
+ {\r
+ }\r
+ \r
+ // Push new gap, move s count bytes further (skipping the gap).\r
+ // Collapse previous gap.\r
+ void push(char_t*& s, size_t count)\r
+ {\r
+ if (end) // there was a gap already; collapse it\r
+ {\r
+ // Move [old_gap_end, new_gap_start) to [old_gap_start, ...)\r
+ assert(s >= end);\r
+ memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));\r
+ }\r
+ \r
+ s += count; // end of current gap\r
+ \r
+ // "merge" two gaps\r
+ end = s;\r
+ size += count;\r
+ }\r
+ \r
+ // Collapse all gaps, return past-the-end pointer\r
+ char_t* flush(char_t* s)\r
+ {\r
+ if (end)\r
+ {\r
+ // Move [old_gap_end, current_pos) to [old_gap_start, ...)\r
+ assert(s >= end);\r
+ memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));\r
+\r
+ return s - size;\r
+ }\r
+ else return s;\r
+ }\r
+ };\r
+ \r
+ PUGI__FN char_t* strconv_escape(char_t* s, gap& g)\r
+ {\r
+ char_t* stre = s + 1;\r
+\r
+ switch (*stre)\r
+ {\r
+ case '#': // &#...\r
+ {\r
+ unsigned int ucsc = 0;\r
+\r
+ if (stre[1] == 'x') // &#x... (hex code)\r
+ {\r
+ stre += 2;\r
+\r
+ char_t ch = *stre;\r
+\r
+ if (ch == ';') return stre;\r
+\r
+ for (;;)\r
+ {\r
+ if (static_cast<unsigned int>(ch - '0') <= 9)\r
+ ucsc = 16 * ucsc + (ch - '0');\r
+ else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5)\r
+ ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10);\r
+ else if (ch == ';')\r
+ break;\r
+ else // cancel\r
+ return stre;\r
+\r
+ ch = *++stre;\r
+ }\r
+ \r
+ ++stre;\r
+ }\r
+ else // &#... (dec code)\r
+ {\r
+ char_t ch = *++stre;\r
+\r
+ if (ch == ';') return stre;\r
+\r
+ for (;;)\r
+ {\r
+ if (static_cast<unsigned int>(static_cast<unsigned int>(ch) - '0') <= 9)\r
+ ucsc = 10 * ucsc + (ch - '0');\r
+ else if (ch == ';')\r
+ break;\r
+ else // cancel\r
+ return stre;\r
+\r
+ ch = *++stre;\r
+ }\r
+ \r
+ ++stre;\r
+ }\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc));\r
+ #else\r
+ s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc));\r
+ #endif\r
+ \r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+\r
+ case 'a': // &a\r
+ {\r
+ ++stre;\r
+\r
+ if (*stre == 'm') // &am\r
+ {\r
+ if (*++stre == 'p' && *++stre == ';') // &\r
+ {\r
+ *s++ = '&';\r
+ ++stre;\r
+ \r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+ }\r
+ else if (*stre == 'p') // &ap\r
+ {\r
+ if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // '\r
+ {\r
+ *s++ = '\'';\r
+ ++stre;\r
+\r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+ }\r
+ break;\r
+ }\r
+\r
+ case 'g': // &g\r
+ {\r
+ if (*++stre == 't' && *++stre == ';') // >\r
+ {\r
+ *s++ = '>';\r
+ ++stre;\r
+ \r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+ break;\r
+ }\r
+\r
+ case 'l': // &l\r
+ {\r
+ if (*++stre == 't' && *++stre == ';') // <\r
+ {\r
+ *s++ = '<';\r
+ ++stre;\r
+ \r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+ break;\r
+ }\r
+\r
+ case 'q': // &q\r
+ {\r
+ if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // "\r
+ {\r
+ *s++ = '"';\r
+ ++stre;\r
+ \r
+ g.push(s, stre - s);\r
+ return stre;\r
+ }\r
+ break;\r
+ }\r
+\r
+ default:\r
+ break;\r
+ }\r
+ \r
+ return stre;\r
+ }\r
+\r
+ // Utility macro for last character handling\r
+ #define ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e)))\r
+\r
+ PUGI__FN char_t* strconv_comment(char_t* s, char_t endch)\r
+ {\r
+ gap g;\r
+ \r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_comment)) ++s;\r
+ \r
+ if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair\r
+ {\r
+ *s++ = '\n'; // replace first one with 0x0a\r
+ \r
+ if (*s == '\n') g.push(s, 1);\r
+ }\r
+ else if (s[0] == '-' && s[1] == '-' && ENDSWITH(s[2], '>')) // comment ends here\r
+ {\r
+ *g.flush(s) = 0;\r
+ \r
+ return s + (s[2] == '>' ? 3 : 2);\r
+ }\r
+ else if (*s == 0)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+\r
+ PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch)\r
+ {\r
+ gap g;\r
+ \r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_cdata)) ++s;\r
+ \r
+ if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair\r
+ {\r
+ *s++ = '\n'; // replace first one with 0x0a\r
+ \r
+ if (*s == '\n') g.push(s, 1);\r
+ }\r
+ else if (s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>')) // CDATA ends here\r
+ {\r
+ *g.flush(s) = 0;\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (*s == 0)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+ \r
+ typedef char_t* (*strconv_pcdata_t)(char_t*);\r
+ \r
+ template <typename opt_trim, typename opt_eol, typename opt_escape> struct strconv_pcdata_impl\r
+ {\r
+ static char_t* parse(char_t* s)\r
+ {\r
+ gap g;\r
+\r
+ char_t* begin = s;\r
+\r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_pcdata)) ++s;\r
+ \r
+ if (*s == '<') // PCDATA ends here\r
+ {\r
+ char_t* end = g.flush(s);\r
+\r
+ if (opt_trim::value)\r
+ while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))\r
+ --end;\r
+\r
+ *end = 0;\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair\r
+ {\r
+ *s++ = '\n'; // replace first one with 0x0a\r
+ \r
+ if (*s == '\n') g.push(s, 1);\r
+ }\r
+ else if (opt_escape::value && *s == '&')\r
+ {\r
+ s = strconv_escape(s, g);\r
+ }\r
+ else if (*s == 0)\r
+ {\r
+ char_t* end = g.flush(s);\r
+\r
+ if (opt_trim::value)\r
+ while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))\r
+ --end;\r
+\r
+ *end = 0;\r
+\r
+ return s;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+ };\r
+ \r
+ PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask)\r
+ {\r
+ PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_trim_pcdata == 0x0800);\r
+\r
+ switch (((optmask >> 4) & 3) | ((optmask >> 9) & 4)) // get bitmask for flags (eol escapes trim)\r
+ {\r
+ case 0: return strconv_pcdata_impl<opt_false, opt_false, opt_false>::parse;\r
+ case 1: return strconv_pcdata_impl<opt_false, opt_false, opt_true>::parse;\r
+ case 2: return strconv_pcdata_impl<opt_false, opt_true, opt_false>::parse;\r
+ case 3: return strconv_pcdata_impl<opt_false, opt_true, opt_true>::parse;\r
+ case 4: return strconv_pcdata_impl<opt_true, opt_false, opt_false>::parse;\r
+ case 5: return strconv_pcdata_impl<opt_true, opt_false, opt_true>::parse;\r
+ case 6: return strconv_pcdata_impl<opt_true, opt_true, opt_false>::parse;\r
+ case 7: return strconv_pcdata_impl<opt_true, opt_true, opt_true>::parse;\r
+ default: assert(false); return 0; // should not get here\r
+ }\r
+ }\r
+\r
+ typedef char_t* (*strconv_attribute_t)(char_t*, char_t);\r
+ \r
+ template <typename opt_escape> struct strconv_attribute_impl\r
+ {\r
+ static char_t* parse_wnorm(char_t* s, char_t end_quote)\r
+ {\r
+ gap g;\r
+\r
+ // trim leading whitespaces\r
+ if (PUGI__IS_CHARTYPE(*s, ct_space))\r
+ {\r
+ char_t* str = s;\r
+ \r
+ do ++str;\r
+ while (PUGI__IS_CHARTYPE(*str, ct_space));\r
+ \r
+ g.push(s, str - s);\r
+ }\r
+\r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr_ws | ct_space)) ++s;\r
+ \r
+ if (*s == end_quote)\r
+ {\r
+ char_t* str = g.flush(s);\r
+ \r
+ do *str-- = 0;\r
+ while (PUGI__IS_CHARTYPE(*str, ct_space));\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (PUGI__IS_CHARTYPE(*s, ct_space))\r
+ {\r
+ *s++ = ' ';\r
+ \r
+ if (PUGI__IS_CHARTYPE(*s, ct_space))\r
+ {\r
+ char_t* str = s + 1;\r
+ while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str;\r
+ \r
+ g.push(s, str - s);\r
+ }\r
+ }\r
+ else if (opt_escape::value && *s == '&')\r
+ {\r
+ s = strconv_escape(s, g);\r
+ }\r
+ else if (!*s)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+\r
+ static char_t* parse_wconv(char_t* s, char_t end_quote)\r
+ {\r
+ gap g;\r
+\r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr_ws)) ++s;\r
+ \r
+ if (*s == end_quote)\r
+ {\r
+ *g.flush(s) = 0;\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (PUGI__IS_CHARTYPE(*s, ct_space))\r
+ {\r
+ if (*s == '\r')\r
+ {\r
+ *s++ = ' ';\r
+ \r
+ if (*s == '\n') g.push(s, 1);\r
+ }\r
+ else *s++ = ' ';\r
+ }\r
+ else if (opt_escape::value && *s == '&')\r
+ {\r
+ s = strconv_escape(s, g);\r
+ }\r
+ else if (!*s)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+\r
+ static char_t* parse_eol(char_t* s, char_t end_quote)\r
+ {\r
+ gap g;\r
+\r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr)) ++s;\r
+ \r
+ if (*s == end_quote)\r
+ {\r
+ *g.flush(s) = 0;\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (*s == '\r')\r
+ {\r
+ *s++ = '\n';\r
+ \r
+ if (*s == '\n') g.push(s, 1);\r
+ }\r
+ else if (opt_escape::value && *s == '&')\r
+ {\r
+ s = strconv_escape(s, g);\r
+ }\r
+ else if (!*s)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+\r
+ static char_t* parse_simple(char_t* s, char_t end_quote)\r
+ {\r
+ gap g;\r
+\r
+ while (true)\r
+ {\r
+ while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr)) ++s;\r
+ \r
+ if (*s == end_quote)\r
+ {\r
+ *g.flush(s) = 0;\r
+ \r
+ return s + 1;\r
+ }\r
+ else if (opt_escape::value && *s == '&')\r
+ {\r
+ s = strconv_escape(s, g);\r
+ }\r
+ else if (!*s)\r
+ {\r
+ return 0;\r
+ }\r
+ else ++s;\r
+ }\r
+ }\r
+ };\r
+\r
+ PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask)\r
+ {\r
+ PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80);\r
+ \r
+ switch ((optmask >> 4) & 15) // get bitmask for flags (wconv wnorm eol escapes)\r
+ {\r
+ case 0: return strconv_attribute_impl<opt_false>::parse_simple;\r
+ case 1: return strconv_attribute_impl<opt_true>::parse_simple;\r
+ case 2: return strconv_attribute_impl<opt_false>::parse_eol;\r
+ case 3: return strconv_attribute_impl<opt_true>::parse_eol;\r
+ case 4: return strconv_attribute_impl<opt_false>::parse_wconv;\r
+ case 5: return strconv_attribute_impl<opt_true>::parse_wconv;\r
+ case 6: return strconv_attribute_impl<opt_false>::parse_wconv;\r
+ case 7: return strconv_attribute_impl<opt_true>::parse_wconv;\r
+ case 8: return strconv_attribute_impl<opt_false>::parse_wnorm;\r
+ case 9: return strconv_attribute_impl<opt_true>::parse_wnorm;\r
+ case 10: return strconv_attribute_impl<opt_false>::parse_wnorm;\r
+ case 11: return strconv_attribute_impl<opt_true>::parse_wnorm;\r
+ case 12: return strconv_attribute_impl<opt_false>::parse_wnorm;\r
+ case 13: return strconv_attribute_impl<opt_true>::parse_wnorm;\r
+ case 14: return strconv_attribute_impl<opt_false>::parse_wnorm;\r
+ case 15: return strconv_attribute_impl<opt_true>::parse_wnorm;\r
+ default: assert(false); return 0; // should not get here\r
+ }\r
+ }\r
+\r
+ inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0)\r
+ {\r
+ xml_parse_result result;\r
+ result.status = status;\r
+ result.offset = offset;\r
+\r
+ return result;\r
+ }\r
+\r
+ struct xml_parser\r
+ {\r
+ xml_allocator alloc;\r
+ char_t* error_offset;\r
+ xml_parse_status error_status;\r
+ \r
+ // Parser utilities.\r
+ #define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; }\r
+ #define PUGI__OPTSET(OPT) ( optmsk & (OPT) )\r
+ #define PUGI__PUSHNODE(TYPE) { cursor = append_node(cursor, alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); }\r
+ #define PUGI__POPNODE() { cursor = cursor->parent; }\r
+ #define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; }\r
+ #define PUGI__SCANWHILE(X) { while ((X)) ++s; }\r
+ #define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; }\r
+ #define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0)\r
+ #define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); }\r
+ \r
+ xml_parser(const xml_allocator& alloc_): alloc(alloc_), error_offset(0), error_status(status_ok)\r
+ {\r
+ }\r
+\r
+ // DOCTYPE consists of nested sections of the following possible types:\r
+ // <!-- ... -->, <? ... ?>, "...", '...'\r
+ // <![...]]>\r
+ // <!...>\r
+ // First group can not contain nested groups\r
+ // Second group can contain nested groups of the same type\r
+ // Third group can contain all other groups\r
+ char_t* parse_doctype_primitive(char_t* s)\r
+ {\r
+ if (*s == '"' || *s == '\'')\r
+ {\r
+ // quoted string\r
+ char_t ch = *s++;\r
+ PUGI__SCANFOR(*s == ch);\r
+ if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ s++;\r
+ }\r
+ else if (s[0] == '<' && s[1] == '?')\r
+ {\r
+ // <? ... ?>\r
+ s += 2;\r
+ PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype\r
+ if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ s += 2;\r
+ }\r
+ else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-')\r
+ {\r
+ s += 4;\r
+ PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype\r
+ if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ s += 4;\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ return s;\r
+ }\r
+\r
+ char_t* parse_doctype_ignore(char_t* s)\r
+ {\r
+ assert(s[0] == '<' && s[1] == '!' && s[2] == '[');\r
+ s++;\r
+\r
+ while (*s)\r
+ {\r
+ if (s[0] == '<' && s[1] == '!' && s[2] == '[')\r
+ {\r
+ // nested ignore section\r
+ s = parse_doctype_ignore(s);\r
+ if (!s) return s;\r
+ }\r
+ else if (s[0] == ']' && s[1] == ']' && s[2] == '>')\r
+ {\r
+ // ignore section end\r
+ s += 3;\r
+\r
+ return s;\r
+ }\r
+ else s++;\r
+ }\r
+\r
+ PUGI__THROW_ERROR(status_bad_doctype, s);\r
+ }\r
+\r
+ char_t* parse_doctype_group(char_t* s, char_t endch, bool toplevel)\r
+ {\r
+ assert((s[0] == '<' || s[0] == 0) && s[1] == '!');\r
+ s++;\r
+\r
+ while (*s)\r
+ {\r
+ if (s[0] == '<' && s[1] == '!' && s[2] != '-')\r
+ {\r
+ if (s[2] == '[')\r
+ {\r
+ // ignore\r
+ s = parse_doctype_ignore(s);\r
+ if (!s) return s;\r
+ }\r
+ else\r
+ {\r
+ // some control group\r
+ s = parse_doctype_group(s, endch, false);\r
+ if (!s) return s;\r
+\r
+ // skip >\r
+ assert(*s == '>');\r
+ s++;\r
+ }\r
+ }\r
+ else if (s[0] == '<' || s[0] == '"' || s[0] == '\'')\r
+ {\r
+ // unknown tag (forbidden), or some primitive group\r
+ s = parse_doctype_primitive(s);\r
+ if (!s) return s;\r
+ }\r
+ else if (*s == '>')\r
+ {\r
+ return s;\r
+ }\r
+ else s++;\r
+ }\r
+\r
+ if (!toplevel || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ return s;\r
+ }\r
+\r
+ char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch)\r
+ {\r
+ // parse node contents, starting with exclamation mark\r
+ ++s;\r
+\r
+ if (*s == '-') // '<!-...'\r
+ {\r
+ ++s;\r
+\r
+ if (*s == '-') // '<!--...'\r
+ {\r
+ ++s;\r
+\r
+ if (PUGI__OPTSET(parse_comments))\r
+ {\r
+ PUGI__PUSHNODE(node_comment); // Append a new node on the tree.\r
+ cursor->value = s; // Save the offset.\r
+ }\r
+\r
+ if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments))\r
+ {\r
+ s = strconv_comment(s, endch);\r
+\r
+ if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value);\r
+ }\r
+ else\r
+ {\r
+ // Scan for terminating '-->'.\r
+ PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && ENDSWITH(s[2], '>'));\r
+ PUGI__CHECK_ERROR(status_bad_comment, s);\r
+\r
+ if (PUGI__OPTSET(parse_comments))\r
+ *s = 0; // Zero-terminate this segment at the first terminating '-'.\r
+\r
+ s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'.\r
+ }\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_comment, s);\r
+ }\r
+ else if (*s == '[')\r
+ {\r
+ // '<![CDATA[...'\r
+ if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[')\r
+ {\r
+ ++s;\r
+\r
+ if (PUGI__OPTSET(parse_cdata))\r
+ {\r
+ PUGI__PUSHNODE(node_cdata); // Append a new node on the tree.\r
+ cursor->value = s; // Save the offset.\r
+\r
+ if (PUGI__OPTSET(parse_eol))\r
+ {\r
+ s = strconv_cdata(s, endch);\r
+\r
+ if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value);\r
+ }\r
+ else\r
+ {\r
+ // Scan for terminating ']]>'.\r
+ PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>'));\r
+ PUGI__CHECK_ERROR(status_bad_cdata, s);\r
+\r
+ *s++ = 0; // Zero-terminate this segment.\r
+ }\r
+ }\r
+ else // Flagged for discard, but we still have to scan for the terminator.\r
+ {\r
+ // Scan for terminating ']]>'.\r
+ PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>'));\r
+ PUGI__CHECK_ERROR(status_bad_cdata, s);\r
+\r
+ ++s;\r
+ }\r
+\r
+ s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'.\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_cdata, s);\r
+ }\r
+ else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && ENDSWITH(s[6], 'E'))\r
+ {\r
+ s -= 2;\r
+\r
+ if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s);\r
+\r
+ char_t* mark = s + 9;\r
+\r
+ s = parse_doctype_group(s, endch, true);\r
+ if (!s) return s;\r
+\r
+ assert((*s == 0 && endch == '>') || *s == '>');\r
+ if (*s) *s++ = 0;\r
+\r
+ if (PUGI__OPTSET(parse_doctype))\r
+ {\r
+ while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark;\r
+\r
+ PUGI__PUSHNODE(node_doctype);\r
+\r
+ cursor->value = mark;\r
+\r
+ PUGI__POPNODE();\r
+ }\r
+ }\r
+ else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s);\r
+ else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s);\r
+ else PUGI__THROW_ERROR(status_unrecognized_tag, s);\r
+\r
+ return s;\r
+ }\r
+\r
+ char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch)\r
+ {\r
+ // load into registers\r
+ xml_node_struct* cursor = ref_cursor;\r
+ char_t ch = 0;\r
+\r
+ // parse node contents, starting with question mark\r
+ ++s;\r
+\r
+ // read PI target\r
+ char_t* target = s;\r
+\r
+ if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s);\r
+\r
+ PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol));\r
+ PUGI__CHECK_ERROR(status_bad_pi, s);\r
+\r
+ // determine node type; stricmp / strcasecmp is not portable\r
+ bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s;\r
+\r
+ if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi))\r
+ {\r
+ if (declaration)\r
+ {\r
+ // disallow non top-level declarations\r
+ if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s);\r
+\r
+ PUGI__PUSHNODE(node_declaration);\r
+ }\r
+ else\r
+ {\r
+ PUGI__PUSHNODE(node_pi);\r
+ }\r
+\r
+ cursor->name = target;\r
+\r
+ PUGI__ENDSEG();\r
+\r
+ // parse value/attributes\r
+ if (ch == '?')\r
+ {\r
+ // empty node\r
+ if (!ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s);\r
+ s += (*s == '>');\r
+\r
+ PUGI__POPNODE();\r
+ }\r
+ else if (PUGI__IS_CHARTYPE(ch, ct_space))\r
+ {\r
+ PUGI__SKIPWS();\r
+\r
+ // scan for tag end\r
+ char_t* value = s;\r
+\r
+ PUGI__SCANFOR(s[0] == '?' && ENDSWITH(s[1], '>'));\r
+ PUGI__CHECK_ERROR(status_bad_pi, s);\r
+\r
+ if (declaration)\r
+ {\r
+ // replace ending ? with / so that 'element' terminates properly\r
+ *s = '/';\r
+\r
+ // we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES\r
+ s = value;\r
+ }\r
+ else\r
+ {\r
+ // store value and step over >\r
+ cursor->value = value;\r
+ PUGI__POPNODE();\r
+\r
+ PUGI__ENDSEG();\r
+\r
+ s += (*s == '>');\r
+ }\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_pi, s);\r
+ }\r
+ else\r
+ {\r
+ // scan for tag end\r
+ PUGI__SCANFOR(s[0] == '?' && ENDSWITH(s[1], '>'));\r
+ PUGI__CHECK_ERROR(status_bad_pi, s);\r
+\r
+ s += (s[1] == '>' ? 2 : 1);\r
+ }\r
+\r
+ // store from registers\r
+ ref_cursor = cursor;\r
+\r
+ return s;\r
+ }\r
+\r
+ char_t* parse_tree(char_t* s, xml_node_struct* root, unsigned int optmsk, char_t endch)\r
+ {\r
+ strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk);\r
+ strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk);\r
+ \r
+ char_t ch = 0;\r
+ xml_node_struct* cursor = root;\r
+ char_t* mark = s;\r
+\r
+ while (*s != 0)\r
+ {\r
+ if (*s == '<')\r
+ {\r
+ ++s;\r
+\r
+ LOC_TAG:\r
+ if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...'\r
+ {\r
+ PUGI__PUSHNODE(node_element); // Append a new node to the tree.\r
+\r
+ cursor->name = s;\r
+\r
+ PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol)); // Scan for a terminator.\r
+ PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.\r
+\r
+ if (ch == '>')\r
+ {\r
+ // end of tag\r
+ }\r
+ else if (PUGI__IS_CHARTYPE(ch, ct_space))\r
+ {\r
+ LOC_ATTRIBUTES:\r
+ while (true)\r
+ {\r
+ PUGI__SKIPWS(); // Eat any whitespace.\r
+ \r
+ if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #...\r
+ {\r
+ xml_attribute_struct* a = append_attribute_ll(cursor, alloc); // Make space for this attribute.\r
+ if (!a) PUGI__THROW_ERROR(status_out_of_memory, s);\r
+\r
+ a->name = s; // Save the offset.\r
+\r
+ PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol)); // Scan for a terminator.\r
+ PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance\r
+\r
+ PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.\r
+ PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance\r
+\r
+ if (PUGI__IS_CHARTYPE(ch, ct_space))\r
+ {\r
+ PUGI__SKIPWS(); // Eat any whitespace.\r
+ PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance\r
+\r
+ ch = *s;\r
+ ++s;\r
+ }\r
+ \r
+ if (ch == '=') // '<... #=...'\r
+ {\r
+ PUGI__SKIPWS(); // Eat any whitespace.\r
+\r
+ if (*s == '"' || *s == '\'') // '<... #="...'\r
+ {\r
+ ch = *s; // Save quote char to avoid breaking on "''" -or- '""'.\r
+ ++s; // Step over the quote.\r
+ a->value = s; // Save the offset.\r
+\r
+ s = strconv_attribute(s, ch);\r
+ \r
+ if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value);\r
+\r
+ // After this line the loop continues from the start;\r
+ // Whitespaces, / and > are ok, symbols and EOF are wrong,\r
+ // everything else will be detected\r
+ if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s);\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_attribute, s);\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_attribute, s);\r
+ }\r
+ else if (*s == '/')\r
+ {\r
+ ++s;\r
+ \r
+ if (*s == '>')\r
+ {\r
+ PUGI__POPNODE();\r
+ s++;\r
+ break;\r
+ }\r
+ else if (*s == 0 && endch == '>')\r
+ {\r
+ PUGI__POPNODE();\r
+ break;\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_start_element, s);\r
+ }\r
+ else if (*s == '>')\r
+ {\r
+ ++s;\r
+\r
+ break;\r
+ }\r
+ else if (*s == 0 && endch == '>')\r
+ {\r
+ break;\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_start_element, s);\r
+ }\r
+\r
+ // !!!\r
+ }\r
+ else if (ch == '/') // '<#.../'\r
+ {\r
+ if (!ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s);\r
+\r
+ PUGI__POPNODE(); // Pop.\r
+\r
+ s += (*s == '>');\r
+ }\r
+ else if (ch == 0)\r
+ {\r
+ // we stepped over null terminator, backtrack & handle closing tag\r
+ --s;\r
+ \r
+ if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s);\r
+ }\r
+ else PUGI__THROW_ERROR(status_bad_start_element, s);\r
+ }\r
+ else if (*s == '/')\r
+ {\r
+ ++s;\r
+\r
+ char_t* name = cursor->name;\r
+ if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, s);\r
+ \r
+ while (PUGI__IS_CHARTYPE(*s, ct_symbol))\r
+ {\r
+ if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, s);\r
+ }\r
+\r
+ if (*name)\r
+ {\r
+ if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s);\r
+ else PUGI__THROW_ERROR(status_end_element_mismatch, s);\r
+ }\r
+ \r
+ PUGI__POPNODE(); // Pop.\r
+\r
+ PUGI__SKIPWS();\r
+\r
+ if (*s == 0)\r
+ {\r
+ if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s);\r
+ }\r
+ else\r
+ {\r
+ if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s);\r
+ ++s;\r
+ }\r
+ }\r
+ else if (*s == '?') // '<?...'\r
+ {\r
+ s = parse_question(s, cursor, optmsk, endch);\r
+ if (!s) return s;\r
+\r
+ assert(cursor);\r
+ if ((cursor->header & xml_memory_page_type_mask) + 1 == node_declaration) goto LOC_ATTRIBUTES;\r
+ }\r
+ else if (*s == '!') // '<!...'\r
+ {\r
+ s = parse_exclamation(s, cursor, optmsk, endch);\r
+ if (!s) return s;\r
+ }\r
+ else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s);\r
+ else PUGI__THROW_ERROR(status_unrecognized_tag, s);\r
+ }\r
+ else\r
+ {\r
+ mark = s; // Save this offset while searching for a terminator.\r
+\r
+ PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here.\r
+\r
+ if (*s == '<' || !*s)\r
+ {\r
+ // We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one\r
+ assert(mark != s);\r
+\r
+ if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single) || PUGI__OPTSET(parse_trim_pcdata))\r
+ {\r
+ continue;\r
+ }\r
+ else if (PUGI__OPTSET(parse_ws_pcdata_single))\r
+ {\r
+ if (s[0] != '<' || s[1] != '/' || cursor->first_child) continue;\r
+ }\r
+ }\r
+\r
+ if (!PUGI__OPTSET(parse_trim_pcdata))\r
+ s = mark;\r
+ \r
+ if (cursor->parent || PUGI__OPTSET(parse_fragment))\r
+ {\r
+ PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree.\r
+ cursor->value = s; // Save the offset.\r
+\r
+ s = strconv_pcdata(s);\r
+ \r
+ PUGI__POPNODE(); // Pop since this is a standalone.\r
+ \r
+ if (!*s) break;\r
+ }\r
+ else\r
+ {\r
+ PUGI__SCANFOR(*s == '<'); // '...<'\r
+ if (!*s) break;\r
+ \r
+ ++s;\r
+ }\r
+\r
+ // We're after '<'\r
+ goto LOC_TAG;\r
+ }\r
+ }\r
+\r
+ // check that last tag is closed\r
+ if (cursor != root) PUGI__THROW_ERROR(status_end_element_mismatch, s);\r
+\r
+ return s;\r
+ }\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ static char_t* parse_skip_bom(char_t* s)\r
+ {\r
+ unsigned int bom = 0xfeff;\r
+ return (s[0] == static_cast<wchar_t>(bom)) ? s + 1 : s;\r
+ }\r
+ #else\r
+ static char_t* parse_skip_bom(char_t* s)\r
+ {\r
+ return (s[0] == '\xef' && s[1] == '\xbb' && s[2] == '\xbf') ? s + 3 : s;\r
+ }\r
+ #endif\r
+\r
+ static bool has_element_node_siblings(xml_node_struct* node)\r
+ {\r
+ while (node)\r
+ {\r
+ xml_node_type type = static_cast<xml_node_type>((node->header & impl::xml_memory_page_type_mask) + 1);\r
+ if (type == node_element) return true;\r
+\r
+ node = node->next_sibling;\r
+ }\r
+\r
+ return false;\r
+ }\r
+\r
+ static xml_parse_result parse(char_t* buffer, size_t length, xml_document_struct* xmldoc, xml_node_struct* root, unsigned int optmsk)\r
+ {\r
+ // allocator object is a part of document object\r
+ xml_allocator& alloc = *static_cast<xml_allocator*>(xmldoc);\r
+\r
+ // early-out for empty documents\r
+ if (length == 0)\r
+ return make_parse_result(PUGI__OPTSET(parse_fragment) ? status_ok : status_no_document_element);\r
+\r
+ // get last child of the root before parsing\r
+ xml_node_struct* last_root_child = root->first_child ? root->first_child->prev_sibling_c : 0;\r
+ \r
+ // create parser on stack\r
+ xml_parser parser(alloc);\r
+\r
+ // save last character and make buffer zero-terminated (speeds up parsing)\r
+ char_t endch = buffer[length - 1];\r
+ buffer[length - 1] = 0;\r
+ \r
+ // skip BOM to make sure it does not end up as part of parse output\r
+ char_t* buffer_data = parse_skip_bom(buffer);\r
+\r
+ // perform actual parsing\r
+ parser.parse_tree(buffer_data, root, optmsk, endch);\r
+\r
+ // update allocator state\r
+ alloc = parser.alloc;\r
+\r
+ xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0);\r
+ assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length);\r
+\r
+ if (result)\r
+ {\r
+ // since we removed last character, we have to handle the only possible false positive (stray <)\r
+ if (endch == '<')\r
+ return make_parse_result(status_unrecognized_tag, length - 1);\r
+\r
+ // check if there are any element nodes parsed\r
+ xml_node_struct* first_root_child_parsed = last_root_child ? last_root_child->next_sibling : root->first_child;\r
+\r
+ if (!PUGI__OPTSET(parse_fragment) && !has_element_node_siblings(first_root_child_parsed))\r
+ return make_parse_result(status_no_document_element, length - 1);\r
+ }\r
+ else\r
+ {\r
+ // roll back offset if it occurs on a null terminator in the source buffer\r
+ if (result.offset > 0 && static_cast<size_t>(result.offset) == length - 1 && endch == 0)\r
+ result.offset--;\r
+ }\r
+\r
+ return result;\r
+ }\r
+ };\r
+\r
+ // Output facilities\r
+ PUGI__FN xml_encoding get_write_native_encoding()\r
+ {\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return get_wchar_encoding();\r
+ #else\r
+ return encoding_utf8;\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding)\r
+ {\r
+ // replace wchar encoding with utf implementation\r
+ if (encoding == encoding_wchar) return get_wchar_encoding();\r
+\r
+ // replace utf16 encoding with utf16 with specific endianness\r
+ if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ // replace utf32 encoding with utf32 with specific endianness\r
+ if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ // only do autodetection if no explicit encoding is requested\r
+ if (encoding != encoding_auto) return encoding;\r
+\r
+ // assume utf8 encoding\r
+ return encoding_utf8;\r
+ }\r
+\r
+#ifdef PUGIXML_WCHAR_MODE\r
+ PUGI__FN size_t get_valid_length(const char_t* data, size_t length)\r
+ {\r
+ assert(length > 0);\r
+\r
+ // discard last character if it's the lead of a surrogate pair \r
+ return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length;\r
+ }\r
+\r
+ PUGI__FN size_t convert_buffer_output(char_t* r_char, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)\r
+ {\r
+ // only endian-swapping is required\r
+ if (need_endian_swap_utf(encoding, get_wchar_encoding()))\r
+ {\r
+ convert_wchar_endian_swap(r_char, data, length);\r
+\r
+ return length * sizeof(char_t);\r
+ }\r
+ \r
+ // convert to utf8\r
+ if (encoding == encoding_utf8)\r
+ {\r
+ uint8_t* dest = r_u8;\r
+ uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(data, length, dest);\r
+\r
+ return static_cast<size_t>(end - dest);\r
+ }\r
+\r
+ // convert to utf16\r
+ if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)\r
+ {\r
+ uint16_t* dest = r_u16;\r
+\r
+ // convert to native utf16\r
+ uint16_t* end = utf_decoder<utf16_writer>::decode_wchar_block(data, length, dest);\r
+\r
+ // swap if necessary\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));\r
+\r
+ return static_cast<size_t>(end - dest) * sizeof(uint16_t);\r
+ }\r
+\r
+ // convert to utf32\r
+ if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)\r
+ {\r
+ uint32_t* dest = r_u32;\r
+\r
+ // convert to native utf32\r
+ uint32_t* end = utf_decoder<utf32_writer>::decode_wchar_block(data, length, dest);\r
+\r
+ // swap if necessary\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));\r
+\r
+ return static_cast<size_t>(end - dest) * sizeof(uint32_t);\r
+ }\r
+\r
+ // convert to latin1\r
+ if (encoding == encoding_latin1)\r
+ {\r
+ uint8_t* dest = r_u8;\r
+ uint8_t* end = utf_decoder<latin1_writer>::decode_wchar_block(data, length, dest);\r
+\r
+ return static_cast<size_t>(end - dest);\r
+ }\r
+\r
+ assert(!"Invalid encoding");\r
+ return 0;\r
+ }\r
+#else\r
+ PUGI__FN size_t get_valid_length(const char_t* data, size_t length)\r
+ {\r
+ assert(length > 4);\r
+\r
+ for (size_t i = 1; i <= 4; ++i)\r
+ {\r
+ uint8_t ch = static_cast<uint8_t>(data[length - i]);\r
+\r
+ // either a standalone character or a leading one\r
+ if ((ch & 0xc0) != 0x80) return length - i;\r
+ }\r
+\r
+ // there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk\r
+ return length;\r
+ }\r
+\r
+ PUGI__FN size_t convert_buffer_output(char_t* /* r_char */, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)\r
+ {\r
+ if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)\r
+ {\r
+ uint16_t* dest = r_u16;\r
+\r
+ // convert to native utf16\r
+ uint16_t* end = utf_decoder<utf16_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);\r
+\r
+ // swap if necessary\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;\r
+\r
+ if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));\r
+\r
+ return static_cast<size_t>(end - dest) * sizeof(uint16_t);\r
+ }\r
+\r
+ if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)\r
+ {\r
+ uint32_t* dest = r_u32;\r
+\r
+ // convert to native utf32\r
+ uint32_t* end = utf_decoder<utf32_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);\r
+\r
+ // swap if necessary\r
+ xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;\r
+\r
+ if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));\r
+\r
+ return static_cast<size_t>(end - dest) * sizeof(uint32_t);\r
+ }\r
+\r
+ if (encoding == encoding_latin1)\r
+ {\r
+ uint8_t* dest = r_u8;\r
+ uint8_t* end = utf_decoder<latin1_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);\r
+\r
+ return static_cast<size_t>(end - dest);\r
+ }\r
+\r
+ assert(!"Invalid encoding");\r
+ return 0;\r
+ }\r
+#endif\r
+\r
+ class xml_buffered_writer\r
+ {\r
+ xml_buffered_writer(const xml_buffered_writer&);\r
+ xml_buffered_writer& operator=(const xml_buffered_writer&);\r
+\r
+ public:\r
+ xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding))\r
+ {\r
+ PUGI__STATIC_ASSERT(bufcapacity >= 8);\r
+ }\r
+\r
+ ~xml_buffered_writer()\r
+ {\r
+ flush();\r
+ }\r
+\r
+ void flush()\r
+ {\r
+ flush(buffer, bufsize);\r
+ bufsize = 0;\r
+ }\r
+\r
+ void flush(const char_t* data, size_t size)\r
+ {\r
+ if (size == 0) return;\r
+\r
+ // fast path, just write data\r
+ if (encoding == get_write_native_encoding())\r
+ writer.write(data, size * sizeof(char_t));\r
+ else\r
+ {\r
+ // convert chunk\r
+ size_t result = convert_buffer_output(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding);\r
+ assert(result <= sizeof(scratch));\r
+\r
+ // write data\r
+ writer.write(scratch.data_u8, result);\r
+ }\r
+ }\r
+\r
+ void write(const char_t* data, size_t length)\r
+ {\r
+ if (bufsize + length > bufcapacity)\r
+ {\r
+ // flush the remaining buffer contents\r
+ flush();\r
+\r
+ // handle large chunks\r
+ if (length > bufcapacity)\r
+ {\r
+ if (encoding == get_write_native_encoding())\r
+ {\r
+ // fast path, can just write data chunk\r
+ writer.write(data, length * sizeof(char_t));\r
+ return;\r
+ }\r
+\r
+ // need to convert in suitable chunks\r
+ while (length > bufcapacity)\r
+ {\r
+ // get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer\r
+ // and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary)\r
+ size_t chunk_size = get_valid_length(data, bufcapacity);\r
+\r
+ // convert chunk and write\r
+ flush(data, chunk_size);\r
+\r
+ // iterate\r
+ data += chunk_size;\r
+ length -= chunk_size;\r
+ }\r
+\r
+ // small tail is copied below\r
+ bufsize = 0;\r
+ }\r
+ }\r
+\r
+ memcpy(buffer + bufsize, data, length * sizeof(char_t));\r
+ bufsize += length;\r
+ }\r
+\r
+ void write(const char_t* data)\r
+ {\r
+ write(data, strlength(data));\r
+ }\r
+\r
+ void write(char_t d0)\r
+ {\r
+ if (bufsize + 1 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ bufsize += 1;\r
+ }\r
+\r
+ void write(char_t d0, char_t d1)\r
+ {\r
+ if (bufsize + 2 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ buffer[bufsize + 1] = d1;\r
+ bufsize += 2;\r
+ }\r
+\r
+ void write(char_t d0, char_t d1, char_t d2)\r
+ {\r
+ if (bufsize + 3 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ buffer[bufsize + 1] = d1;\r
+ buffer[bufsize + 2] = d2;\r
+ bufsize += 3;\r
+ }\r
+\r
+ void write(char_t d0, char_t d1, char_t d2, char_t d3)\r
+ {\r
+ if (bufsize + 4 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ buffer[bufsize + 1] = d1;\r
+ buffer[bufsize + 2] = d2;\r
+ buffer[bufsize + 3] = d3;\r
+ bufsize += 4;\r
+ }\r
+\r
+ void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4)\r
+ {\r
+ if (bufsize + 5 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ buffer[bufsize + 1] = d1;\r
+ buffer[bufsize + 2] = d2;\r
+ buffer[bufsize + 3] = d3;\r
+ buffer[bufsize + 4] = d4;\r
+ bufsize += 5;\r
+ }\r
+\r
+ void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5)\r
+ {\r
+ if (bufsize + 6 > bufcapacity) flush();\r
+\r
+ buffer[bufsize + 0] = d0;\r
+ buffer[bufsize + 1] = d1;\r
+ buffer[bufsize + 2] = d2;\r
+ buffer[bufsize + 3] = d3;\r
+ buffer[bufsize + 4] = d4;\r
+ buffer[bufsize + 5] = d5;\r
+ bufsize += 6;\r
+ }\r
+\r
+ // utf8 maximum expansion: x4 (-> utf32)\r
+ // utf16 maximum expansion: x2 (-> utf32)\r
+ // utf32 maximum expansion: x1\r
+ enum\r
+ {\r
+ bufcapacitybytes =\r
+ #ifdef PUGIXML_MEMORY_OUTPUT_STACK\r
+ PUGIXML_MEMORY_OUTPUT_STACK\r
+ #else\r
+ 10240\r
+ #endif\r
+ ,\r
+ bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4)\r
+ };\r
+\r
+ char_t buffer[bufcapacity];\r
+\r
+ union\r
+ {\r
+ uint8_t data_u8[4 * bufcapacity];\r
+ uint16_t data_u16[2 * bufcapacity];\r
+ uint32_t data_u32[bufcapacity];\r
+ char_t data_char[bufcapacity];\r
+ } scratch;\r
+\r
+ xml_writer& writer;\r
+ size_t bufsize;\r
+ xml_encoding encoding;\r
+ };\r
+\r
+ PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type)\r
+ {\r
+ while (*s)\r
+ {\r
+ const char_t* prev = s;\r
+ \r
+ // While *s is a usual symbol\r
+ while (!PUGI__IS_CHARTYPEX(*s, type)) ++s;\r
+ \r
+ writer.write(prev, static_cast<size_t>(s - prev));\r
+\r
+ switch (*s)\r
+ {\r
+ case 0: break;\r
+ case '&':\r
+ writer.write('&', 'a', 'm', 'p', ';');\r
+ ++s;\r
+ break;\r
+ case '<':\r
+ writer.write('&', 'l', 't', ';');\r
+ ++s;\r
+ break;\r
+ case '>':\r
+ writer.write('&', 'g', 't', ';');\r
+ ++s;\r
+ break;\r
+ case '"':\r
+ writer.write('&', 'q', 'u', 'o', 't', ';');\r
+ ++s;\r
+ break;\r
+ default: // s is not a usual symbol\r
+ {\r
+ unsigned int ch = static_cast<unsigned int>(*s++);\r
+ assert(ch < 32);\r
+\r
+ writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)\r
+ {\r
+ if (flags & format_no_escapes)\r
+ writer.write(s);\r
+ else\r
+ text_output_escaped(writer, s, type);\r
+ }\r
+\r
+ PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)\r
+ {\r
+ do\r
+ {\r
+ writer.write('<', '!', '[', 'C', 'D');\r
+ writer.write('A', 'T', 'A', '[');\r
+\r
+ const char_t* prev = s;\r
+\r
+ // look for ]]> sequence - we can't output it as is since it terminates CDATA\r
+ while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;\r
+\r
+ // skip ]] if we stopped at ]]>, > will go to the next CDATA section\r
+ if (*s) s += 2;\r
+\r
+ writer.write(prev, static_cast<size_t>(s - prev));\r
+\r
+ writer.write(']', ']', '>');\r
+ }\r
+ while (*s);\r
+ }\r
+\r
+ PUGI__FN void node_output_attributes(xml_buffered_writer& writer, const xml_node& node, unsigned int flags)\r
+ {\r
+ const char_t* default_name = PUGIXML_TEXT(":anonymous");\r
+\r
+ for (xml_attribute a = node.first_attribute(); a; a = a.next_attribute())\r
+ {\r
+ writer.write(' ');\r
+ writer.write(a.name()[0] ? a.name() : default_name);\r
+ writer.write('=', '"');\r
+\r
+ text_output(writer, a.value(), ctx_special_attr, flags);\r
+\r
+ writer.write('"');\r
+ }\r
+ }\r
+\r
+ PUGI__FN void node_output(xml_buffered_writer& writer, const xml_node& node, const char_t* indent, unsigned int flags, unsigned int depth)\r
+ {\r
+ const char_t* default_name = PUGIXML_TEXT(":anonymous");\r
+\r
+ if ((flags & format_indent) != 0 && (flags & format_raw) == 0)\r
+ for (unsigned int i = 0; i < depth; ++i) writer.write(indent);\r
+\r
+ switch (node.type())\r
+ {\r
+ case node_document:\r
+ {\r
+ for (xml_node n = node.first_child(); n; n = n.next_sibling())\r
+ node_output(writer, n, indent, flags, depth);\r
+ break;\r
+ }\r
+ \r
+ case node_element:\r
+ {\r
+ const char_t* name = node.name()[0] ? node.name() : default_name;\r
+\r
+ writer.write('<');\r
+ writer.write(name);\r
+\r
+ node_output_attributes(writer, node, flags);\r
+\r
+ if (flags & format_raw)\r
+ {\r
+ if (!node.first_child())\r
+ writer.write(' ', '/', '>');\r
+ else\r
+ {\r
+ writer.write('>');\r
+\r
+ for (xml_node n = node.first_child(); n; n = n.next_sibling())\r
+ node_output(writer, n, indent, flags, depth + 1);\r
+\r
+ writer.write('<', '/');\r
+ writer.write(name);\r
+ writer.write('>');\r
+ }\r
+ }\r
+ else if (!node.first_child())\r
+ writer.write(' ', '/', '>', '\n');\r
+ else if (node.first_child() == node.last_child() && (node.first_child().type() == node_pcdata || node.first_child().type() == node_cdata))\r
+ {\r
+ writer.write('>');\r
+\r
+ if (node.first_child().type() == node_pcdata)\r
+ text_output(writer, node.first_child().value(), ctx_special_pcdata, flags);\r
+ else\r
+ text_output_cdata(writer, node.first_child().value());\r
+\r
+ writer.write('<', '/');\r
+ writer.write(name);\r
+ writer.write('>', '\n');\r
+ }\r
+ else\r
+ {\r
+ writer.write('>', '\n');\r
+ \r
+ for (xml_node n = node.first_child(); n; n = n.next_sibling())\r
+ node_output(writer, n, indent, flags, depth + 1);\r
+\r
+ if ((flags & format_indent) != 0 && (flags & format_raw) == 0)\r
+ for (unsigned int i = 0; i < depth; ++i) writer.write(indent);\r
+ \r
+ writer.write('<', '/');\r
+ writer.write(name);\r
+ writer.write('>', '\n');\r
+ }\r
+\r
+ break;\r
+ }\r
+ \r
+ case node_pcdata:\r
+ text_output(writer, node.value(), ctx_special_pcdata, flags);\r
+ if ((flags & format_raw) == 0) writer.write('\n');\r
+ break;\r
+\r
+ case node_cdata:\r
+ text_output_cdata(writer, node.value());\r
+ if ((flags & format_raw) == 0) writer.write('\n');\r
+ break;\r
+\r
+ case node_comment:\r
+ writer.write('<', '!', '-', '-');\r
+ writer.write(node.value());\r
+ writer.write('-', '-', '>');\r
+ if ((flags & format_raw) == 0) writer.write('\n');\r
+ break;\r
+\r
+ case node_pi:\r
+ case node_declaration:\r
+ writer.write('<', '?');\r
+ writer.write(node.name()[0] ? node.name() : default_name);\r
+\r
+ if (node.type() == node_declaration)\r
+ {\r
+ node_output_attributes(writer, node, flags);\r
+ }\r
+ else if (node.value()[0])\r
+ {\r
+ writer.write(' ');\r
+ writer.write(node.value());\r
+ }\r
+\r
+ writer.write('?', '>');\r
+ if ((flags & format_raw) == 0) writer.write('\n');\r
+ break;\r
+\r
+ case node_doctype:\r
+ writer.write('<', '!', 'D', 'O', 'C');\r
+ writer.write('T', 'Y', 'P', 'E');\r
+\r
+ if (node.value()[0])\r
+ {\r
+ writer.write(' ');\r
+ writer.write(node.value());\r
+ }\r
+\r
+ writer.write('>');\r
+ if ((flags & format_raw) == 0) writer.write('\n');\r
+ break;\r
+\r
+ default:\r
+ assert(!"Invalid node type");\r
+ }\r
+ }\r
+\r
+ inline bool has_declaration(const xml_node& node)\r
+ {\r
+ for (xml_node child = node.first_child(); child; child = child.next_sibling())\r
+ {\r
+ xml_node_type type = child.type();\r
+\r
+ if (type == node_declaration) return true;\r
+ if (type == node_element) return false;\r
+ }\r
+\r
+ return false;\r
+ }\r
+\r
+ inline bool allow_insert_child(xml_node_type parent, xml_node_type child)\r
+ {\r
+ if (parent != node_document && parent != node_element) return false;\r
+ if (child == node_document || child == node_null) return false;\r
+ if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN void recursive_copy_skip(xml_node& dest, const xml_node& source, const xml_node& skip)\r
+ {\r
+ assert(dest.type() == source.type());\r
+\r
+ switch (source.type())\r
+ {\r
+ case node_element:\r
+ {\r
+ dest.set_name(source.name());\r
+\r
+ for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())\r
+ dest.append_attribute(a.name()).set_value(a.value());\r
+\r
+ for (xml_node c = source.first_child(); c; c = c.next_sibling())\r
+ {\r
+ if (c == skip) continue;\r
+\r
+ xml_node cc = dest.append_child(c.type());\r
+ assert(cc);\r
+\r
+ recursive_copy_skip(cc, c, skip);\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ case node_pcdata:\r
+ case node_cdata:\r
+ case node_comment:\r
+ case node_doctype:\r
+ dest.set_value(source.value());\r
+ break;\r
+\r
+ case node_pi:\r
+ dest.set_name(source.name());\r
+ dest.set_value(source.value());\r
+ break;\r
+\r
+ case node_declaration:\r
+ {\r
+ dest.set_name(source.name());\r
+\r
+ for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())\r
+ dest.append_attribute(a.name()).set_value(a.value());\r
+\r
+ break;\r
+ }\r
+\r
+ default:\r
+ assert(!"Invalid node type");\r
+ }\r
+ }\r
+\r
+ inline bool is_text_node(xml_node_struct* node)\r
+ {\r
+ xml_node_type type = static_cast<xml_node_type>((node->header & impl::xml_memory_page_type_mask) + 1);\r
+\r
+ return type == node_pcdata || type == node_cdata;\r
+ }\r
+\r
+ // get value with conversion functions\r
+ PUGI__FN int get_integer_base(const char_t* value)\r
+ {\r
+ const char_t* s = value;\r
+\r
+ while (PUGI__IS_CHARTYPE(*s, ct_space))\r
+ s++;\r
+\r
+ if (*s == '-')\r
+ s++;\r
+\r
+ return (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? 16 : 10;\r
+ }\r
+\r
+ PUGI__FN int get_value_int(const char_t* value, int def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ int base = get_integer_base(value);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return static_cast<int>(wcstol(value, 0, base));\r
+ #else\r
+ return static_cast<int>(strtol(value, 0, base));\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN unsigned int get_value_uint(const char_t* value, unsigned int def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ int base = get_integer_base(value);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return static_cast<unsigned int>(wcstoul(value, 0, base));\r
+ #else\r
+ return static_cast<unsigned int>(strtoul(value, 0, base));\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN double get_value_double(const char_t* value, double def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcstod(value, 0);\r
+ #else\r
+ return strtod(value, 0);\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN float get_value_float(const char_t* value, float def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return static_cast<float>(wcstod(value, 0));\r
+ #else\r
+ return static_cast<float>(strtod(value, 0));\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN bool get_value_bool(const char_t* value, bool def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ // only look at first char\r
+ char_t first = *value;\r
+\r
+ // 1*, t* (true), T* (True), y* (yes), Y* (YES)\r
+ return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN long long get_value_llong(const char_t* value, long long def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ int base = get_integer_base(value);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ #ifdef PUGI__MSVC_CRT_VERSION\r
+ return _wcstoi64(value, 0, base);\r
+ #else\r
+ return wcstoll(value, 0, base);\r
+ #endif\r
+ #else\r
+ #ifdef PUGI__MSVC_CRT_VERSION\r
+ return _strtoi64(value, 0, base);\r
+ #else\r
+ return strtoll(value, 0, base);\r
+ #endif\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN unsigned long long get_value_ullong(const char_t* value, unsigned long long def)\r
+ {\r
+ if (!value) return def;\r
+\r
+ int base = get_integer_base(value);\r
+\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ #ifdef PUGI__MSVC_CRT_VERSION\r
+ return _wcstoui64(value, 0, base);\r
+ #else\r
+ return wcstoull(value, 0, base);\r
+ #endif\r
+ #else\r
+ #ifdef PUGI__MSVC_CRT_VERSION\r
+ return _strtoui64(value, 0, base);\r
+ #else\r
+ return strtoull(value, 0, base);\r
+ #endif\r
+ #endif\r
+ }\r
+#endif\r
+\r
+ // set value with conversion functions\r
+ PUGI__FN bool set_value_buffer(char_t*& dest, uintptr_t& header, uintptr_t header_mask, char (&buf)[128])\r
+ {\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ char_t wbuf[128];\r
+ impl::widen_ascii(wbuf, buf);\r
+\r
+ return strcpy_insitu(dest, header, header_mask, wbuf);\r
+ #else\r
+ return strcpy_insitu(dest, header, header_mask, buf);\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value)\r
+ {\r
+ char buf[128];\r
+ sprintf(buf, "%d", value);\r
+ \r
+ return set_value_buffer(dest, header, header_mask, buf);\r
+ }\r
+\r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned int value)\r
+ {\r
+ char buf[128];\r
+ sprintf(buf, "%u", value);\r
+\r
+ return set_value_buffer(dest, header, header_mask, buf);\r
+ }\r
+\r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, double value)\r
+ {\r
+ char buf[128];\r
+ sprintf(buf, "%g", value);\r
+\r
+ return set_value_buffer(dest, header, header_mask, buf);\r
+ }\r
+ \r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, bool value)\r
+ {\r
+ return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, long long value)\r
+ {\r
+ char buf[128];\r
+ sprintf(buf, "%lld", value);\r
+ \r
+ return set_value_buffer(dest, header, header_mask, buf);\r
+ }\r
+\r
+ PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned long long value)\r
+ {\r
+ char buf[128];\r
+ sprintf(buf, "%llu", value);\r
+ \r
+ return set_value_buffer(dest, header, header_mask, buf);\r
+ }\r
+#endif\r
+\r
+ // we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick\r
+ PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)\r
+ {\r
+ #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)\r
+ // there are 64-bit versions of fseek/ftell, let's use them\r
+ typedef __int64 length_type;\r
+\r
+ _fseeki64(file, 0, SEEK_END);\r
+ length_type length = _ftelli64(file);\r
+ _fseeki64(file, 0, SEEK_SET);\r
+ #elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && !defined(__STRICT_ANSI__)\r
+ // there are 64-bit versions of fseek/ftell, let's use them\r
+ typedef off64_t length_type;\r
+\r
+ fseeko64(file, 0, SEEK_END);\r
+ length_type length = ftello64(file);\r
+ fseeko64(file, 0, SEEK_SET);\r
+ #else\r
+ // if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway.\r
+ typedef long length_type;\r
+\r
+ fseek(file, 0, SEEK_END);\r
+ length_type length = ftell(file);\r
+ fseek(file, 0, SEEK_SET);\r
+ #endif\r
+\r
+ // check for I/O errors\r
+ if (length < 0) return status_io_error;\r
+ \r
+ // check for overflow\r
+ size_t result = static_cast<size_t>(length);\r
+\r
+ if (static_cast<length_type>(result) != length) return status_out_of_memory;\r
+\r
+ // finalize\r
+ out_result = result;\r
+\r
+ return status_ok;\r
+ }\r
+\r
+ PUGI__FN size_t zero_terminate_buffer(void* buffer, size_t size, xml_encoding encoding) \r
+ {\r
+ // We only need to zero-terminate if encoding conversion does not do it for us\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ xml_encoding wchar_encoding = get_wchar_encoding();\r
+\r
+ if (encoding == wchar_encoding || need_endian_swap_utf(encoding, wchar_encoding))\r
+ {\r
+ size_t length = size / sizeof(char_t);\r
+\r
+ static_cast<char_t*>(buffer)[length] = 0;\r
+ return (length + 1) * sizeof(char_t);\r
+ }\r
+ #else\r
+ if (encoding == encoding_utf8)\r
+ {\r
+ static_cast<char*>(buffer)[size] = 0;\r
+ return size + 1;\r
+ }\r
+ #endif\r
+\r
+ return size;\r
+ }\r
+\r
+ PUGI__FN xml_parse_result load_file_impl(xml_document& doc, FILE* file, unsigned int options, xml_encoding encoding)\r
+ {\r
+ if (!file) return make_parse_result(status_file_not_found);\r
+\r
+ // get file size (can result in I/O errors)\r
+ size_t size = 0;\r
+ xml_parse_status size_status = get_file_size(file, size);\r
+\r
+ if (size_status != status_ok)\r
+ {\r
+ fclose(file);\r
+ return make_parse_result(size_status);\r
+ }\r
+ \r
+ size_t max_suffix_size = sizeof(char_t);\r
+\r
+ // allocate buffer for the whole file\r
+ char* contents = static_cast<char*>(xml_memory::allocate(size + max_suffix_size));\r
+\r
+ if (!contents)\r
+ {\r
+ fclose(file);\r
+ return make_parse_result(status_out_of_memory);\r
+ }\r
+\r
+ // read file in memory\r
+ size_t read_size = fread(contents, 1, size, file);\r
+ fclose(file);\r
+\r
+ if (read_size != size)\r
+ {\r
+ xml_memory::deallocate(contents);\r
+ return make_parse_result(status_io_error);\r
+ }\r
+\r
+ xml_encoding real_encoding = get_buffer_encoding(encoding, contents, size);\r
+ \r
+ return doc.load_buffer_inplace_own(contents, zero_terminate_buffer(contents, size, real_encoding), options, real_encoding);\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ template <typename T> struct xml_stream_chunk\r
+ {\r
+ static xml_stream_chunk* create()\r
+ {\r
+ void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));\r
+ \r
+ return new (memory) xml_stream_chunk();\r
+ }\r
+\r
+ static void destroy(void* ptr)\r
+ {\r
+ xml_stream_chunk* chunk = static_cast<xml_stream_chunk*>(ptr);\r
+\r
+ // free chunk chain\r
+ while (chunk)\r
+ {\r
+ xml_stream_chunk* next = chunk->next;\r
+ xml_memory::deallocate(chunk);\r
+ chunk = next;\r
+ }\r
+ }\r
+\r
+ xml_stream_chunk(): next(0), size(0)\r
+ {\r
+ }\r
+\r
+ xml_stream_chunk* next;\r
+ size_t size;\r
+\r
+ T data[xml_memory_page_size / sizeof(T)];\r
+ };\r
+\r
+ template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)\r
+ {\r
+ buffer_holder chunks(0, xml_stream_chunk<T>::destroy);\r
+\r
+ // read file to a chunk list\r
+ size_t total = 0;\r
+ xml_stream_chunk<T>* last = 0;\r
+\r
+ while (!stream.eof())\r
+ {\r
+ // allocate new chunk\r
+ xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();\r
+ if (!chunk) return status_out_of_memory;\r
+\r
+ // append chunk to list\r
+ if (last) last = last->next = chunk;\r
+ else chunks.data = last = chunk;\r
+\r
+ // read data to chunk\r
+ stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));\r
+ chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);\r
+\r
+ // read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors\r
+ if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;\r
+\r
+ // guard against huge files (chunk size is small enough to make this overflow check work)\r
+ if (total + chunk->size < total) return status_out_of_memory;\r
+ total += chunk->size;\r
+ }\r
+\r
+ size_t max_suffix_size = sizeof(char_t);\r
+\r
+ // copy chunk list to a contiguous buffer\r
+ char* buffer = static_cast<char*>(xml_memory::allocate(total + max_suffix_size));\r
+ if (!buffer) return status_out_of_memory;\r
+\r
+ char* write = buffer;\r
+\r
+ for (xml_stream_chunk<T>* chunk = static_cast<xml_stream_chunk<T>*>(chunks.data); chunk; chunk = chunk->next)\r
+ {\r
+ assert(write + chunk->size <= buffer + total);\r
+ memcpy(write, chunk->data, chunk->size);\r
+ write += chunk->size;\r
+ }\r
+\r
+ assert(write == buffer + total);\r
+\r
+ // return buffer\r
+ *out_buffer = buffer;\r
+ *out_size = total;\r
+\r
+ return status_ok;\r
+ }\r
+\r
+ template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)\r
+ {\r
+ // get length of remaining data in stream\r
+ typename std::basic_istream<T>::pos_type pos = stream.tellg();\r
+ stream.seekg(0, std::ios::end);\r
+ std::streamoff length = stream.tellg() - pos;\r
+ stream.seekg(pos);\r
+\r
+ if (stream.fail() || pos < 0) return status_io_error;\r
+\r
+ // guard against huge files\r
+ size_t read_length = static_cast<size_t>(length);\r
+\r
+ if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;\r
+\r
+ size_t max_suffix_size = sizeof(char_t);\r
+\r
+ // read stream data into memory (guard against stream exceptions with buffer holder)\r
+ buffer_holder buffer(xml_memory::allocate(read_length * sizeof(T) + max_suffix_size), xml_memory::deallocate);\r
+ if (!buffer.data) return status_out_of_memory;\r
+\r
+ stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));\r
+\r
+ // read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors\r
+ if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;\r
+\r
+ // return buffer\r
+ size_t actual_length = static_cast<size_t>(stream.gcount());\r
+ assert(actual_length <= read_length);\r
+ \r
+ *out_buffer = buffer.release();\r
+ *out_size = actual_length * sizeof(T);\r
+\r
+ return status_ok;\r
+ }\r
+\r
+ template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document& doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding)\r
+ {\r
+ void* buffer = 0;\r
+ size_t size = 0;\r
+ xml_parse_status status = status_ok;\r
+\r
+ // if stream has an error bit set, bail out (otherwise tellg() can fail and we'll clear error bits)\r
+ if (stream.fail()) return make_parse_result(status_io_error);\r
+\r
+ // load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)\r
+ if (stream.tellg() < 0)\r
+ {\r
+ stream.clear(); // clear error flags that could be set by a failing tellg\r
+ status = load_stream_data_noseek(stream, &buffer, &size);\r
+ }\r
+ else\r
+ status = load_stream_data_seek(stream, &buffer, &size);\r
+\r
+ if (status != status_ok) return make_parse_result(status);\r
+\r
+ xml_encoding real_encoding = get_buffer_encoding(encoding, buffer, size);\r
+ \r
+ return doc.load_buffer_inplace_own(buffer, zero_terminate_buffer(buffer, size, real_encoding), options, real_encoding);\r
+ }\r
+#endif\r
+\r
+#if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && !defined(__STRICT_ANSI__))\r
+ PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)\r
+ {\r
+ return _wfopen(path, mode);\r
+ }\r
+#else\r
+ PUGI__FN char* convert_path_heap(const wchar_t* str)\r
+ {\r
+ assert(str);\r
+\r
+ // first pass: get length in utf8 characters\r
+ size_t length = strlength_wide(str);\r
+ size_t size = as_utf8_begin(str, length);\r
+\r
+ // allocate resulting string\r
+ char* result = static_cast<char*>(xml_memory::allocate(size + 1));\r
+ if (!result) return 0;\r
+\r
+ // second pass: convert to utf8\r
+ as_utf8_end(result, size, str, length);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)\r
+ {\r
+ // there is no standard function to open wide paths, so our best bet is to try utf8 path\r
+ char* path_utf8 = convert_path_heap(path);\r
+ if (!path_utf8) return 0;\r
+\r
+ // convert mode to ASCII (we mirror _wfopen interface)\r
+ char mode_ascii[4] = {0};\r
+ for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);\r
+\r
+ // try to open the utf8 path\r
+ FILE* result = fopen(path_utf8, mode_ascii);\r
+\r
+ // free dummy buffer\r
+ xml_memory::deallocate(path_utf8);\r
+\r
+ return result;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)\r
+ {\r
+ if (!file) return false;\r
+\r
+ xml_writer_file writer(file);\r
+ doc.save(writer, indent, flags, encoding);\r
+\r
+ int result = ferror(file);\r
+\r
+ fclose(file);\r
+\r
+ return result == 0;\r
+ }\r
+\r
+ PUGI__FN xml_parse_result load_buffer_impl(xml_document_struct* doc, xml_node_struct* root, void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own, char_t** out_buffer)\r
+ {\r
+ // check input buffer\r
+ assert(contents || size == 0);\r
+\r
+ // get actual encoding\r
+ xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size);\r
+\r
+ // get private buffer\r
+ char_t* buffer = 0;\r
+ size_t length = 0;\r
+\r
+ if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory);\r
+ \r
+ // delete original buffer if we performed a conversion\r
+ if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents);\r
+\r
+ // store buffer for offset_debug\r
+ doc->buffer = buffer;\r
+\r
+ // parse\r
+ xml_parse_result res = impl::xml_parser::parse(buffer, length, doc, root, options);\r
+\r
+ // remember encoding\r
+ res.encoding = buffer_encoding;\r
+\r
+ // grab onto buffer if it's our buffer, user is responsible for deallocating contents himself\r
+ if (own || buffer != contents) *out_buffer = buffer;\r
+\r
+ return res;\r
+ }\r
+PUGI__NS_END\r
+\r
+namespace pugi\r
+{\r
+ PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)\r
+ {\r
+ }\r
+\r
+ PUGI__FN void xml_writer_file::write(const void* data, size_t size)\r
+ {\r
+ size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));\r
+ (void)!result; // unfortunately we can't do proper error handling here\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream)\r
+ {\r
+ }\r
+\r
+ PUGI__FN void xml_writer_stream::write(const void* data, size_t size)\r
+ {\r
+ if (narrow_stream)\r
+ {\r
+ assert(!wide_stream);\r
+ narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));\r
+ }\r
+ else\r
+ {\r
+ assert(wide_stream);\r
+ assert(size % sizeof(wchar_t) == 0);\r
+\r
+ wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));\r
+ }\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)\r
+ {\r
+ }\r
+ \r
+ PUGI__FN xml_tree_walker::~xml_tree_walker()\r
+ {\r
+ }\r
+\r
+ PUGI__FN int xml_tree_walker::depth() const\r
+ {\r
+ return _depth;\r
+ }\r
+\r
+ PUGI__FN bool xml_tree_walker::begin(xml_node&)\r
+ {\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool xml_tree_walker::end(xml_node&)\r
+ {\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN xml_attribute::xml_attribute(): _attr(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)\r
+ {\r
+ }\r
+\r
+ PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const\r
+ {\r
+ return _attr ? unspecified_bool_xml_attribute : 0;\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::operator!() const\r
+ {\r
+ return !_attr;\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const\r
+ {\r
+ return (_attr == r._attr);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const\r
+ {\r
+ return (_attr != r._attr);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const\r
+ {\r
+ return (_attr < r._attr);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const\r
+ {\r
+ return (_attr > r._attr);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const\r
+ {\r
+ return (_attr <= r._attr);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const\r
+ {\r
+ return (_attr >= r._attr);\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_attribute::next_attribute() const\r
+ {\r
+ return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_attribute::previous_attribute() const\r
+ {\r
+ return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const\r
+ {\r
+ return (_attr && _attr->value) ? _attr->value : def;\r
+ }\r
+\r
+ PUGI__FN int xml_attribute::as_int(int def) const\r
+ {\r
+ return impl::get_value_int(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const\r
+ {\r
+ return impl::get_value_uint(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN double xml_attribute::as_double(double def) const\r
+ {\r
+ return impl::get_value_double(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN float xml_attribute::as_float(float def) const\r
+ {\r
+ return impl::get_value_float(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::as_bool(bool def) const\r
+ {\r
+ return impl::get_value_bool(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN long long xml_attribute::as_llong(long long def) const\r
+ {\r
+ return impl::get_value_llong(_attr ? _attr->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN unsigned long long xml_attribute::as_ullong(unsigned long long def) const\r
+ {\r
+ return impl::get_value_ullong(_attr ? _attr->value : 0, def);\r
+ }\r
+#endif\r
+\r
+ PUGI__FN bool xml_attribute::empty() const\r
+ {\r
+ return !_attr;\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_attribute::name() const\r
+ {\r
+ return (_attr && _attr->name) ? _attr->name : PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_attribute::value() const\r
+ {\r
+ return (_attr && _attr->value) ? _attr->value : PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN size_t xml_attribute::hash_value() const\r
+ {\r
+ return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));\r
+ }\r
+\r
+ PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const\r
+ {\r
+ return _attr;\r
+ }\r
+\r
+ PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+ \r
+ PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+ \r
+ PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN xml_attribute& xml_attribute::operator=(long long rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long long rhs)\r
+ {\r
+ set_value(rhs);\r
+ return *this;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN bool xml_attribute::set_name(const char_t* rhs)\r
+ {\r
+ if (!_attr) return false;\r
+ \r
+ return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::set_value(const char_t* rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::set_value(int rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::set_value(unsigned int rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::set_value(double rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute::set_value(bool rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN bool xml_attribute::set_value(long long rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute::set_value(unsigned long long rhs)\r
+ {\r
+ if (!_attr) return false;\r
+\r
+ return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+ }\r
+#endif\r
+\r
+#ifdef __BORLANDC__\r
+ PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs && rhs;\r
+ }\r
+\r
+ PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs || rhs;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_node::xml_node(): _root(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)\r
+ {\r
+ }\r
+ \r
+ PUGI__FN static void unspecified_bool_xml_node(xml_node***)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const\r
+ {\r
+ return _root ? unspecified_bool_xml_node : 0;\r
+ }\r
+\r
+ PUGI__FN bool xml_node::operator!() const\r
+ {\r
+ return !_root;\r
+ }\r
+\r
+ PUGI__FN xml_node::iterator xml_node::begin() const\r
+ {\r
+ return iterator(_root ? _root->first_child : 0, _root);\r
+ }\r
+\r
+ PUGI__FN xml_node::iterator xml_node::end() const\r
+ {\r
+ return iterator(0, _root);\r
+ }\r
+ \r
+ PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const\r
+ {\r
+ return attribute_iterator(_root ? _root->first_attribute : 0, _root);\r
+ }\r
+\r
+ PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const\r
+ {\r
+ return attribute_iterator(0, _root);\r
+ }\r
+ \r
+ PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const\r
+ {\r
+ return xml_object_range<xml_node_iterator>(begin(), end());\r
+ }\r
+\r
+ PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const\r
+ {\r
+ return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_)._root, _root, name_), xml_named_node_iterator(0, _root, name_));\r
+ }\r
+\r
+ PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const\r
+ {\r
+ return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());\r
+ }\r
+\r
+ PUGI__FN bool xml_node::operator==(const xml_node& r) const\r
+ {\r
+ return (_root == r._root);\r
+ }\r
+\r
+ PUGI__FN bool xml_node::operator!=(const xml_node& r) const\r
+ {\r
+ return (_root != r._root);\r
+ }\r
+\r
+ PUGI__FN bool xml_node::operator<(const xml_node& r) const\r
+ {\r
+ return (_root < r._root);\r
+ }\r
+ \r
+ PUGI__FN bool xml_node::operator>(const xml_node& r) const\r
+ {\r
+ return (_root > r._root);\r
+ }\r
+ \r
+ PUGI__FN bool xml_node::operator<=(const xml_node& r) const\r
+ {\r
+ return (_root <= r._root);\r
+ }\r
+ \r
+ PUGI__FN bool xml_node::operator>=(const xml_node& r) const\r
+ {\r
+ return (_root >= r._root);\r
+ }\r
+\r
+ PUGI__FN bool xml_node::empty() const\r
+ {\r
+ return !_root;\r
+ }\r
+ \r
+ PUGI__FN const char_t* xml_node::name() const\r
+ {\r
+ return (_root && _root->name) ? _root->name : PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN xml_node_type xml_node::type() const\r
+ {\r
+ return _root ? static_cast<xml_node_type>((_root->header & impl::xml_memory_page_type_mask) + 1) : node_null;\r
+ }\r
+ \r
+ PUGI__FN const char_t* xml_node::value() const\r
+ {\r
+ return (_root && _root->value) ? _root->value : PUGIXML_TEXT("");\r
+ }\r
+ \r
+ PUGI__FN xml_node xml_node::child(const char_t* name_) const\r
+ {\r
+ if (!_root) return xml_node();\r
+\r
+ for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)\r
+ if (i->name && impl::strequal(name_, i->name)) return xml_node(i);\r
+\r
+ return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const\r
+ {\r
+ if (!_root) return xml_attribute();\r
+\r
+ for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute)\r
+ if (i->name && impl::strequal(name_, i->name))\r
+ return xml_attribute(i);\r
+ \r
+ return xml_attribute();\r
+ }\r
+ \r
+ PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling)\r
+ if (i->name && impl::strequal(name_, i->name)) return xml_node(i);\r
+\r
+ return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::next_sibling() const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ if (_root->next_sibling) return xml_node(_root->next_sibling);\r
+ else return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c)\r
+ if (i->name && impl::strequal(name_, i->name)) return xml_node(i);\r
+\r
+ return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::previous_sibling() const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c);\r
+ else return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::parent() const\r
+ {\r
+ return _root ? xml_node(_root->parent) : xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::root() const\r
+ {\r
+ if (!_root) return xml_node();\r
+\r
+ impl::xml_memory_page* page = reinterpret_cast<impl::xml_memory_page*>(_root->header & impl::xml_memory_page_pointer_mask);\r
+\r
+ return xml_node(static_cast<impl::xml_document_struct*>(page->allocator));\r
+ }\r
+\r
+ PUGI__FN xml_text xml_node::text() const\r
+ {\r
+ return xml_text(_root);\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_node::child_value() const\r
+ {\r
+ if (!_root) return PUGIXML_TEXT("");\r
+ \r
+ for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)\r
+ if (i->value && impl::is_text_node(i))\r
+ return i->value;\r
+\r
+ return PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const\r
+ {\r
+ return child(name_).child_value();\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::first_attribute() const\r
+ {\r
+ return _root ? xml_attribute(_root->first_attribute) : xml_attribute();\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::last_attribute() const\r
+ {\r
+ return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::first_child() const\r
+ {\r
+ return _root ? xml_node(_root->first_child) : xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::last_child() const\r
+ {\r
+ return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node();\r
+ }\r
+\r
+ PUGI__FN bool xml_node::set_name(const char_t* rhs)\r
+ {\r
+ switch (type())\r
+ {\r
+ case node_pi:\r
+ case node_declaration:\r
+ case node_element:\r
+ return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs);\r
+\r
+ default:\r
+ return false;\r
+ }\r
+ }\r
+ \r
+ PUGI__FN bool xml_node::set_value(const char_t* rhs)\r
+ {\r
+ switch (type())\r
+ {\r
+ case node_pi:\r
+ case node_cdata:\r
+ case node_pcdata:\r
+ case node_comment:\r
+ case node_doctype:\r
+ return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs);\r
+\r
+ default:\r
+ return false;\r
+ }\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_)\r
+ {\r
+ if (type() != node_element && type() != node_declaration) return xml_attribute();\r
+ \r
+ xml_attribute a(impl::append_attribute_ll(_root, impl::get_allocator(_root)));\r
+ a.set_name(name_);\r
+ \r
+ return a;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_)\r
+ {\r
+ if (type() != node_element && type() != node_declaration) return xml_attribute();\r
+ \r
+ xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));\r
+ if (!a) return xml_attribute();\r
+\r
+ a.set_name(name_);\r
+ \r
+ xml_attribute_struct* head = _root->first_attribute;\r
+\r
+ if (head)\r
+ {\r
+ a._attr->prev_attribute_c = head->prev_attribute_c;\r
+ head->prev_attribute_c = a._attr;\r
+ }\r
+ else\r
+ a._attr->prev_attribute_c = a._attr;\r
+ \r
+ a._attr->next_attribute = head;\r
+ _root->first_attribute = a._attr;\r
+ \r
+ return a;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr)\r
+ {\r
+ if ((type() != node_element && type() != node_declaration) || attr.empty()) return xml_attribute();\r
+ \r
+ // check that attribute belongs to *this\r
+ xml_attribute_struct* cur = attr._attr;\r
+\r
+ while (cur->prev_attribute_c->next_attribute) cur = cur->prev_attribute_c;\r
+\r
+ if (cur != _root->first_attribute) return xml_attribute();\r
+\r
+ xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));\r
+ if (!a) return xml_attribute();\r
+\r
+ a.set_name(name_);\r
+\r
+ if (attr._attr->prev_attribute_c->next_attribute)\r
+ attr._attr->prev_attribute_c->next_attribute = a._attr;\r
+ else\r
+ _root->first_attribute = a._attr;\r
+ \r
+ a._attr->prev_attribute_c = attr._attr->prev_attribute_c;\r
+ a._attr->next_attribute = attr._attr;\r
+ attr._attr->prev_attribute_c = a._attr;\r
+ \r
+ return a;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr)\r
+ {\r
+ if ((type() != node_element && type() != node_declaration) || attr.empty()) return xml_attribute();\r
+ \r
+ // check that attribute belongs to *this\r
+ xml_attribute_struct* cur = attr._attr;\r
+\r
+ while (cur->prev_attribute_c->next_attribute) cur = cur->prev_attribute_c;\r
+\r
+ if (cur != _root->first_attribute) return xml_attribute();\r
+\r
+ xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));\r
+ if (!a) return xml_attribute();\r
+\r
+ a.set_name(name_);\r
+\r
+ if (attr._attr->next_attribute)\r
+ attr._attr->next_attribute->prev_attribute_c = a._attr;\r
+ else\r
+ _root->first_attribute->prev_attribute_c = a._attr;\r
+ \r
+ a._attr->next_attribute = attr._attr->next_attribute;\r
+ a._attr->prev_attribute_c = attr._attr;\r
+ attr._attr->next_attribute = a._attr;\r
+\r
+ return a;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto)\r
+ {\r
+ if (!proto) return xml_attribute();\r
+\r
+ xml_attribute result = append_attribute(proto.name());\r
+ result.set_value(proto.value());\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto)\r
+ {\r
+ if (!proto) return xml_attribute();\r
+\r
+ xml_attribute result = prepend_attribute(proto.name());\r
+ result.set_value(proto.value());\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr)\r
+ {\r
+ if (!proto) return xml_attribute();\r
+\r
+ xml_attribute result = insert_attribute_after(proto.name(), attr);\r
+ result.set_value(proto.value());\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr)\r
+ {\r
+ if (!proto) return xml_attribute();\r
+\r
+ xml_attribute result = insert_attribute_before(proto.name(), attr);\r
+ result.set_value(proto.value());\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::append_child(xml_node_type type_)\r
+ {\r
+ if (!impl::allow_insert_child(this->type(), type_)) return xml_node();\r
+ \r
+ xml_node n(impl::append_node(_root, impl::get_allocator(_root), type_));\r
+\r
+ if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));\r
+\r
+ return n;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_)\r
+ {\r
+ if (!impl::allow_insert_child(this->type(), type_)) return xml_node();\r
+ \r
+ xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));\r
+ if (!n) return xml_node();\r
+\r
+ n._root->parent = _root;\r
+\r
+ xml_node_struct* head = _root->first_child;\r
+\r
+ if (head)\r
+ {\r
+ n._root->prev_sibling_c = head->prev_sibling_c;\r
+ head->prev_sibling_c = n._root;\r
+ }\r
+ else\r
+ n._root->prev_sibling_c = n._root;\r
+ \r
+ n._root->next_sibling = head;\r
+ _root->first_child = n._root;\r
+ \r
+ if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));\r
+\r
+ return n;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node)\r
+ {\r
+ if (!impl::allow_insert_child(this->type(), type_)) return xml_node();\r
+ if (!node._root || node._root->parent != _root) return xml_node();\r
+ \r
+ xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));\r
+ if (!n) return xml_node();\r
+\r
+ n._root->parent = _root;\r
+ \r
+ if (node._root->prev_sibling_c->next_sibling)\r
+ node._root->prev_sibling_c->next_sibling = n._root;\r
+ else\r
+ _root->first_child = n._root;\r
+ \r
+ n._root->prev_sibling_c = node._root->prev_sibling_c;\r
+ n._root->next_sibling = node._root;\r
+ node._root->prev_sibling_c = n._root;\r
+\r
+ if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));\r
+\r
+ return n;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node)\r
+ {\r
+ if (!impl::allow_insert_child(this->type(), type_)) return xml_node();\r
+ if (!node._root || node._root->parent != _root) return xml_node();\r
+ \r
+ xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));\r
+ if (!n) return xml_node();\r
+\r
+ n._root->parent = _root;\r
+ \r
+ if (node._root->next_sibling)\r
+ node._root->next_sibling->prev_sibling_c = n._root;\r
+ else\r
+ _root->first_child->prev_sibling_c = n._root;\r
+ \r
+ n._root->next_sibling = node._root->next_sibling;\r
+ n._root->prev_sibling_c = node._root;\r
+ node._root->next_sibling = n._root;\r
+\r
+ if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));\r
+\r
+ return n;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::append_child(const char_t* name_)\r
+ {\r
+ xml_node result = append_child(node_element);\r
+\r
+ result.set_name(name_);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::prepend_child(const char_t* name_)\r
+ {\r
+ xml_node result = prepend_child(node_element);\r
+\r
+ result.set_name(name_);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node)\r
+ {\r
+ xml_node result = insert_child_after(node_element, node);\r
+\r
+ result.set_name(name_);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node)\r
+ {\r
+ xml_node result = insert_child_before(node_element, node);\r
+\r
+ result.set_name(name_);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::append_copy(const xml_node& proto)\r
+ {\r
+ xml_node result = append_child(proto.type());\r
+\r
+ if (result) impl::recursive_copy_skip(result, proto, result);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto)\r
+ {\r
+ xml_node result = prepend_child(proto.type());\r
+\r
+ if (result) impl::recursive_copy_skip(result, proto, result);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node)\r
+ {\r
+ xml_node result = insert_child_after(proto.type(), node);\r
+\r
+ if (result) impl::recursive_copy_skip(result, proto, result);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node)\r
+ {\r
+ xml_node result = insert_child_before(proto.type(), node);\r
+\r
+ if (result) impl::recursive_copy_skip(result, proto, result);\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN bool xml_node::remove_attribute(const char_t* name_)\r
+ {\r
+ return remove_attribute(attribute(name_));\r
+ }\r
+\r
+ PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a)\r
+ {\r
+ if (!_root || !a._attr) return false;\r
+\r
+ // check that attribute belongs to *this\r
+ xml_attribute_struct* attr = a._attr;\r
+\r
+ while (attr->prev_attribute_c->next_attribute) attr = attr->prev_attribute_c;\r
+\r
+ if (attr != _root->first_attribute) return false;\r
+\r
+ if (a._attr->next_attribute) a._attr->next_attribute->prev_attribute_c = a._attr->prev_attribute_c;\r
+ else if (_root->first_attribute) _root->first_attribute->prev_attribute_c = a._attr->prev_attribute_c;\r
+ \r
+ if (a._attr->prev_attribute_c->next_attribute) a._attr->prev_attribute_c->next_attribute = a._attr->next_attribute;\r
+ else _root->first_attribute = a._attr->next_attribute;\r
+\r
+ impl::destroy_attribute(a._attr, impl::get_allocator(_root));\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool xml_node::remove_child(const char_t* name_)\r
+ {\r
+ return remove_child(child(name_));\r
+ }\r
+\r
+ PUGI__FN bool xml_node::remove_child(const xml_node& n)\r
+ {\r
+ if (!_root || !n._root || n._root->parent != _root) return false;\r
+\r
+ if (n._root->next_sibling) n._root->next_sibling->prev_sibling_c = n._root->prev_sibling_c;\r
+ else if (_root->first_child) _root->first_child->prev_sibling_c = n._root->prev_sibling_c;\r
+ \r
+ if (n._root->prev_sibling_c->next_sibling) n._root->prev_sibling_c->next_sibling = n._root->next_sibling;\r
+ else _root->first_child = n._root->next_sibling;\r
+ \r
+ impl::destroy_node(n._root, impl::get_allocator(_root));\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_node::append_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)\r
+ {\r
+ // append_buffer is only valid for elements/documents\r
+ if (!impl::allow_insert_child(type(), node_element)) return impl::make_parse_result(status_append_invalid_root);\r
+\r
+ // get document node\r
+ impl::xml_document_struct* doc = static_cast<impl::xml_document_struct*>(root()._root);\r
+ assert(doc);\r
+ \r
+ // get extra buffer element (we'll store the document fragment buffer there so that we can deallocate it later)\r
+ impl::xml_memory_page* page = 0;\r
+ impl::xml_extra_buffer* extra = static_cast<impl::xml_extra_buffer*>(doc->allocate_memory(sizeof(impl::xml_extra_buffer), page));\r
+ (void)page;\r
+\r
+ if (!extra) return impl::make_parse_result(status_out_of_memory);\r
+\r
+ // save name; name of the root has to be NULL before parsing - otherwise closing node mismatches will not be detected at the top level\r
+ char_t* rootname = _root->name;\r
+ _root->name = 0;\r
+\r
+ // parse\r
+ char_t* buffer = 0;\r
+ xml_parse_result res = impl::load_buffer_impl(doc, _root, const_cast<void*>(contents), size, options, encoding, false, false, &buffer);\r
+\r
+ // restore name\r
+ _root->name = rootname;\r
+\r
+ // add extra buffer to the list\r
+ extra->buffer = buffer;\r
+ extra->next = doc->extra_buffers;\r
+ doc->extra_buffers = extra;\r
+\r
+ return res;\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* name_, const char_t* attr_name, const char_t* attr_value) const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)\r
+ if (i->name && impl::strequal(name_, i->name))\r
+ {\r
+ for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)\r
+ if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value : PUGIXML_TEXT("")))\r
+ return xml_node(i);\r
+ }\r
+\r
+ return xml_node();\r
+ }\r
+\r
+ PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const\r
+ {\r
+ if (!_root) return xml_node();\r
+ \r
+ for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)\r
+ for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)\r
+ if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value : PUGIXML_TEXT("")))\r
+ return xml_node(i);\r
+\r
+ return xml_node();\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN string_t xml_node::path(char_t delimiter) const\r
+ {\r
+ xml_node cursor = *this; // Make a copy.\r
+ \r
+ string_t result = cursor.name();\r
+\r
+ while (cursor.parent())\r
+ {\r
+ cursor = cursor.parent();\r
+ \r
+ string_t temp = cursor.name();\r
+ temp += delimiter;\r
+ temp += result;\r
+ result.swap(temp);\r
+ }\r
+\r
+ return result;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const\r
+ {\r
+ xml_node found = *this; // Current search context.\r
+\r
+ if (!_root || !path_ || !path_[0]) return found;\r
+\r
+ if (path_[0] == delimiter)\r
+ {\r
+ // Absolute path; e.g. '/foo/bar'\r
+ found = found.root();\r
+ ++path_;\r
+ }\r
+\r
+ const char_t* path_segment = path_;\r
+\r
+ while (*path_segment == delimiter) ++path_segment;\r
+\r
+ const char_t* path_segment_end = path_segment;\r
+\r
+ while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end;\r
+\r
+ if (path_segment == path_segment_end) return found;\r
+\r
+ const char_t* next_segment = path_segment_end;\r
+\r
+ while (*next_segment == delimiter) ++next_segment;\r
+\r
+ if (*path_segment == '.' && path_segment + 1 == path_segment_end)\r
+ return found.first_element_by_path(next_segment, delimiter);\r
+ else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end)\r
+ return found.parent().first_element_by_path(next_segment, delimiter);\r
+ else\r
+ {\r
+ for (xml_node_struct* j = found._root->first_child; j; j = j->next_sibling)\r
+ {\r
+ if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment)))\r
+ {\r
+ xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter);\r
+\r
+ if (subsearch) return subsearch;\r
+ }\r
+ }\r
+\r
+ return xml_node();\r
+ }\r
+ }\r
+\r
+ PUGI__FN bool xml_node::traverse(xml_tree_walker& walker)\r
+ {\r
+ walker._depth = -1;\r
+ \r
+ xml_node arg_begin = *this;\r
+ if (!walker.begin(arg_begin)) return false;\r
+\r
+ xml_node cur = first_child();\r
+ \r
+ if (cur)\r
+ {\r
+ ++walker._depth;\r
+\r
+ do \r
+ {\r
+ xml_node arg_for_each = cur;\r
+ if (!walker.for_each(arg_for_each))\r
+ return false;\r
+ \r
+ if (cur.first_child())\r
+ {\r
+ ++walker._depth;\r
+ cur = cur.first_child();\r
+ }\r
+ else if (cur.next_sibling())\r
+ cur = cur.next_sibling();\r
+ else\r
+ {\r
+ // Borland C++ workaround\r
+ while (!cur.next_sibling() && cur != *this && !cur.parent().empty())\r
+ {\r
+ --walker._depth;\r
+ cur = cur.parent();\r
+ }\r
+ \r
+ if (cur != *this)\r
+ cur = cur.next_sibling();\r
+ }\r
+ }\r
+ while (cur && cur != *this);\r
+ }\r
+\r
+ assert(walker._depth == -1);\r
+\r
+ xml_node arg_end = *this;\r
+ return walker.end(arg_end);\r
+ }\r
+\r
+ PUGI__FN size_t xml_node::hash_value() const\r
+ {\r
+ return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct));\r
+ }\r
+\r
+ PUGI__FN xml_node_struct* xml_node::internal_object() const\r
+ {\r
+ return _root;\r
+ }\r
+\r
+ PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const\r
+ {\r
+ if (!_root) return;\r
+\r
+ impl::xml_buffered_writer buffered_writer(writer, encoding);\r
+\r
+ impl::node_output(buffered_writer, *this, indent, flags, depth);\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN void xml_node::print(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const\r
+ {\r
+ xml_writer_stream writer(stream);\r
+\r
+ print(writer, indent, flags, encoding, depth);\r
+ }\r
+\r
+ PUGI__FN void xml_node::print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags, unsigned int depth) const\r
+ {\r
+ xml_writer_stream writer(stream);\r
+\r
+ print(writer, indent, flags, encoding_wchar, depth);\r
+ }\r
+#endif\r
+\r
+ PUGI__FN ptrdiff_t xml_node::offset_debug() const\r
+ {\r
+ xml_node_struct* r = root()._root;\r
+\r
+ if (!r) return -1;\r
+\r
+ const char_t* buffer = static_cast<impl::xml_document_struct*>(r)->buffer;\r
+\r
+ if (!buffer) return -1;\r
+\r
+ switch (type())\r
+ {\r
+ case node_document:\r
+ return 0;\r
+\r
+ case node_element:\r
+ case node_declaration:\r
+ case node_pi:\r
+ return (_root->header & impl::xml_memory_page_name_allocated_mask) ? -1 : _root->name - buffer;\r
+\r
+ case node_pcdata:\r
+ case node_cdata:\r
+ case node_comment:\r
+ case node_doctype:\r
+ return (_root->header & impl::xml_memory_page_value_allocated_mask) ? -1 : _root->value - buffer;\r
+\r
+ default:\r
+ return -1;\r
+ }\r
+ }\r
+\r
+#ifdef __BORLANDC__\r
+ PUGI__FN bool operator&&(const xml_node& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs && rhs;\r
+ }\r
+\r
+ PUGI__FN bool operator||(const xml_node& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs || rhs;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node_struct* xml_text::_data() const\r
+ {\r
+ if (!_root || impl::is_text_node(_root)) return _root;\r
+\r
+ for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling)\r
+ if (impl::is_text_node(node))\r
+ return node;\r
+\r
+ return 0;\r
+ }\r
+\r
+ PUGI__FN xml_node_struct* xml_text::_data_new()\r
+ {\r
+ xml_node_struct* d = _data();\r
+ if (d) return d;\r
+\r
+ return xml_node(_root).append_child(node_pcdata).internal_object();\r
+ }\r
+\r
+ PUGI__FN xml_text::xml_text(): _root(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN static void unspecified_bool_xml_text(xml_text***)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const\r
+ {\r
+ return _data() ? unspecified_bool_xml_text : 0;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::operator!() const\r
+ {\r
+ return !_data();\r
+ }\r
+\r
+ PUGI__FN bool xml_text::empty() const\r
+ {\r
+ return _data() == 0;\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_text::get() const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return (d && d->value) ? d->value : PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const char_t* xml_text::as_string(const char_t* def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return (d && d->value) ? d->value : def;\r
+ }\r
+\r
+ PUGI__FN int xml_text::as_int(int def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_int(d ? d->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_uint(d ? d->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN double xml_text::as_double(double def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_double(d ? d->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN float xml_text::as_float(float def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_float(d ? d->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN bool xml_text::as_bool(bool def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_bool(d ? d->value : 0, def);\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN long long xml_text::as_llong(long long def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_llong(d ? d->value : 0, def);\r
+ }\r
+\r
+ PUGI__FN unsigned long long xml_text::as_ullong(unsigned long long def) const\r
+ {\r
+ xml_node_struct* d = _data();\r
+\r
+ return impl::get_value_ullong(d ? d->value : 0, def);\r
+ }\r
+#endif\r
+\r
+ PUGI__FN bool xml_text::set(const char_t* rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::set(int rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::set(unsigned int rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::set(double rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::set(bool rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN bool xml_text::set(long long rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+\r
+ PUGI__FN bool xml_text::set(unsigned long long rhs)\r
+ {\r
+ xml_node_struct* dn = _data_new();\r
+\r
+ return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(const char_t* rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(int rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(unsigned int rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(double rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(bool rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+#ifdef PUGIXML_HAS_LONG_LONG\r
+ PUGI__FN xml_text& xml_text::operator=(long long rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_text& xml_text::operator=(unsigned long long rhs)\r
+ {\r
+ set(rhs);\r
+ return *this;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_node xml_text::data() const\r
+ {\r
+ return xml_node(_data());\r
+ }\r
+\r
+#ifdef __BORLANDC__\r
+ PUGI__FN bool operator&&(const xml_text& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs && rhs;\r
+ }\r
+\r
+ PUGI__FN bool operator||(const xml_text& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs || rhs;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_node_iterator::xml_node_iterator()\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent())\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)\r
+ {\r
+ }\r
+\r
+ PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const\r
+ {\r
+ return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;\r
+ }\r
+ \r
+ PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const\r
+ {\r
+ return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;\r
+ }\r
+\r
+ PUGI__FN xml_node& xml_node_iterator::operator*() const\r
+ {\r
+ assert(_wrap._root);\r
+ return _wrap;\r
+ }\r
+\r
+ PUGI__FN xml_node* xml_node_iterator::operator->() const\r
+ {\r
+ assert(_wrap._root);\r
+ return const_cast<xml_node*>(&_wrap); // BCC32 workaround\r
+ }\r
+\r
+ PUGI__FN const xml_node_iterator& xml_node_iterator::operator++()\r
+ {\r
+ assert(_wrap._root);\r
+ _wrap._root = _wrap._root->next_sibling;\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_node_iterator xml_node_iterator::operator++(int)\r
+ {\r
+ xml_node_iterator temp = *this;\r
+ ++*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN const xml_node_iterator& xml_node_iterator::operator--()\r
+ {\r
+ _wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child();\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_node_iterator xml_node_iterator::operator--(int)\r
+ {\r
+ xml_node_iterator temp = *this;\r
+ --*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN xml_attribute_iterator::xml_attribute_iterator()\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)\r
+ {\r
+ }\r
+\r
+ PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const\r
+ {\r
+ return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root;\r
+ }\r
+ \r
+ PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const\r
+ {\r
+ return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root;\r
+ }\r
+\r
+ PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const\r
+ {\r
+ assert(_wrap._attr);\r
+ return _wrap;\r
+ }\r
+\r
+ PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const\r
+ {\r
+ assert(_wrap._attr);\r
+ return const_cast<xml_attribute*>(&_wrap); // BCC32 workaround\r
+ }\r
+\r
+ PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++()\r
+ {\r
+ assert(_wrap._attr);\r
+ _wrap._attr = _wrap._attr->next_attribute;\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int)\r
+ {\r
+ xml_attribute_iterator temp = *this;\r
+ ++*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--()\r
+ {\r
+ _wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute();\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int)\r
+ {\r
+ xml_attribute_iterator temp = *this;\r
+ --*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _wrap(node), _parent(node.parent()), _name(name)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_named_node_iterator::xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name): _wrap(ref), _parent(parent), _name(name)\r
+ {\r
+ }\r
+\r
+ PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const\r
+ {\r
+ return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;\r
+ }\r
+\r
+ PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const\r
+ {\r
+ return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;\r
+ }\r
+\r
+ PUGI__FN xml_node& xml_named_node_iterator::operator*() const\r
+ {\r
+ assert(_wrap._root);\r
+ return _wrap;\r
+ }\r
+\r
+ PUGI__FN xml_node* xml_named_node_iterator::operator->() const\r
+ {\r
+ assert(_wrap._root);\r
+ return const_cast<xml_node*>(&_wrap); // BCC32 workaround\r
+ }\r
+\r
+ PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++()\r
+ {\r
+ assert(_wrap._root);\r
+ _wrap = _wrap.next_sibling(_name);\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int)\r
+ {\r
+ xml_named_node_iterator temp = *this;\r
+ ++*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator--()\r
+ {\r
+ if (_wrap._root)\r
+ _wrap = _wrap.previous_sibling(_name);\r
+ else\r
+ {\r
+ _wrap = _parent.last_child();\r
+\r
+ if (!impl::strequal(_wrap.name(), _name))\r
+ _wrap = _wrap.previous_sibling(_name);\r
+ }\r
+\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator--(int)\r
+ {\r
+ xml_named_node_iterator temp = *this;\r
+ --*this;\r
+ return temp;\r
+ }\r
+\r
+ PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_parse_result::operator bool() const\r
+ {\r
+ return status == status_ok;\r
+ }\r
+\r
+ PUGI__FN const char* xml_parse_result::description() const\r
+ {\r
+ switch (status)\r
+ {\r
+ case status_ok: return "No error";\r
+\r
+ case status_file_not_found: return "File was not found";\r
+ case status_io_error: return "Error reading from file/stream";\r
+ case status_out_of_memory: return "Could not allocate memory";\r
+ case status_internal_error: return "Internal error occurred";\r
+\r
+ case status_unrecognized_tag: return "Could not determine tag type";\r
+\r
+ case status_bad_pi: return "Error parsing document declaration/processing instruction";\r
+ case status_bad_comment: return "Error parsing comment";\r
+ case status_bad_cdata: return "Error parsing CDATA section";\r
+ case status_bad_doctype: return "Error parsing document type declaration";\r
+ case status_bad_pcdata: return "Error parsing PCDATA section";\r
+ case status_bad_start_element: return "Error parsing start element tag";\r
+ case status_bad_attribute: return "Error parsing element attribute";\r
+ case status_bad_end_element: return "Error parsing end element tag";\r
+ case status_end_element_mismatch: return "Start-end tags mismatch";\r
+\r
+ case status_append_invalid_root: return "Unable to append nodes: root is not an element or document";\r
+\r
+ case status_no_document_element: return "No document element found";\r
+\r
+ default: return "Unknown error";\r
+ }\r
+ }\r
+\r
+ PUGI__FN xml_document::xml_document(): _buffer(0)\r
+ {\r
+ create();\r
+ }\r
+\r
+ PUGI__FN xml_document::~xml_document()\r
+ {\r
+ destroy();\r
+ }\r
+\r
+ PUGI__FN void xml_document::reset()\r
+ {\r
+ destroy();\r
+ create();\r
+ }\r
+\r
+ PUGI__FN void xml_document::reset(const xml_document& proto)\r
+ {\r
+ reset();\r
+\r
+ for (xml_node cur = proto.first_child(); cur; cur = cur.next_sibling())\r
+ append_copy(cur);\r
+ }\r
+\r
+ PUGI__FN void xml_document::create()\r
+ {\r
+ assert(!_root);\r
+\r
+ // initialize sentinel page\r
+ PUGI__STATIC_ASSERT(sizeof(impl::xml_memory_page) + sizeof(impl::xml_document_struct) + impl::xml_memory_page_alignment <= sizeof(_memory));\r
+\r
+ // align upwards to page boundary\r
+ void* page_memory = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(_memory) + (impl::xml_memory_page_alignment - 1)) & ~(impl::xml_memory_page_alignment - 1));\r
+\r
+ // prepare page structure\r
+ impl::xml_memory_page* page = impl::xml_memory_page::construct(page_memory);\r
+ assert(page);\r
+\r
+ page->busy_size = impl::xml_memory_page_size;\r
+\r
+ // allocate new root\r
+ _root = new (page->data) impl::xml_document_struct(page);\r
+ _root->prev_sibling_c = _root;\r
+\r
+ // setup sentinel page\r
+ page->allocator = static_cast<impl::xml_document_struct*>(_root);\r
+ }\r
+\r
+ PUGI__FN void xml_document::destroy()\r
+ {\r
+ assert(_root);\r
+\r
+ // destroy static storage\r
+ if (_buffer)\r
+ {\r
+ impl::xml_memory::deallocate(_buffer);\r
+ _buffer = 0;\r
+ }\r
+\r
+ // destroy extra buffers (note: no need to destroy linked list nodes, they're allocated using document allocator)\r
+ for (impl::xml_extra_buffer* extra = static_cast<impl::xml_document_struct*>(_root)->extra_buffers; extra; extra = extra->next)\r
+ {\r
+ if (extra->buffer) impl::xml_memory::deallocate(extra->buffer);\r
+ }\r
+\r
+ // destroy dynamic storage, leave sentinel page (it's in static memory)\r
+ impl::xml_memory_page* root_page = reinterpret_cast<impl::xml_memory_page*>(_root->header & impl::xml_memory_page_pointer_mask);\r
+ assert(root_page && !root_page->prev && !root_page->memory);\r
+\r
+ for (impl::xml_memory_page* page = root_page->next; page; )\r
+ {\r
+ impl::xml_memory_page* next = page->next;\r
+\r
+ impl::xml_allocator::deallocate_page(page);\r
+\r
+ page = next;\r
+ }\r
+\r
+ _root = 0;\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ return impl::load_stream_impl(*this, stream, options, encoding);\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options)\r
+ {\r
+ reset();\r
+\r
+ return impl::load_stream_impl(*this, stream, options, encoding_wchar);\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options)\r
+ {\r
+ // Force native encoding (skip autodetection)\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ xml_encoding encoding = encoding_wchar;\r
+ #else\r
+ xml_encoding encoding = encoding_utf8;\r
+ #endif\r
+\r
+ return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding);\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ FILE* file = fopen(path_, "rb");\r
+\r
+ return impl::load_file_impl(*this, file, options, encoding);\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ FILE* file = impl::open_file_wide(path_, L"rb");\r
+\r
+ return impl::load_file_impl(*this, file, options, encoding);\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, const_cast<void*>(contents), size, options, encoding, false, false, &_buffer);\r
+ }\r
+\r
+ PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, false, &_buffer);\r
+ }\r
+ \r
+ PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding)\r
+ {\r
+ reset();\r
+\r
+ return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, true, &_buffer);\r
+ }\r
+\r
+ PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const\r
+ {\r
+ impl::xml_buffered_writer buffered_writer(writer, encoding);\r
+\r
+ if ((flags & format_write_bom) && encoding != encoding_latin1)\r
+ {\r
+ // BOM always represents the codepoint U+FEFF, so just write it in native encoding\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ unsigned int bom = 0xfeff;\r
+ buffered_writer.write(static_cast<wchar_t>(bom));\r
+ #else\r
+ buffered_writer.write('\xef', '\xbb', '\xbf');\r
+ #endif\r
+ }\r
+\r
+ if (!(flags & format_no_declaration) && !impl::has_declaration(*this))\r
+ {\r
+ buffered_writer.write(PUGIXML_TEXT("<?xml version=\"1.0\""));\r
+ if (encoding == encoding_latin1) buffered_writer.write(PUGIXML_TEXT(" encoding=\"ISO-8859-1\""));\r
+ buffered_writer.write('?', '>');\r
+ if (!(flags & format_raw)) buffered_writer.write('\n');\r
+ }\r
+\r
+ impl::node_output(buffered_writer, *this, indent, flags, 0);\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN void xml_document::save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding) const\r
+ {\r
+ xml_writer_stream writer(stream);\r
+\r
+ save(writer, indent, flags, encoding);\r
+ }\r
+\r
+ PUGI__FN void xml_document::save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags) const\r
+ {\r
+ xml_writer_stream writer(stream);\r
+\r
+ save(writer, indent, flags, encoding_wchar);\r
+ }\r
+#endif\r
+\r
+ PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const\r
+ {\r
+ FILE* file = fopen(path_, (flags & format_save_file_text) ? "w" : "wb");\r
+ return impl::save_file_impl(*this, file, indent, flags, encoding);\r
+ }\r
+\r
+ PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const\r
+ {\r
+ FILE* file = impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb");\r
+ return impl::save_file_impl(*this, file, indent, flags, encoding);\r
+ }\r
+\r
+ PUGI__FN xml_node xml_document::document_element() const\r
+ {\r
+ assert(_root);\r
+\r
+ for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)\r
+ if ((i->header & impl::xml_memory_page_type_mask) + 1 == node_element)\r
+ return xml_node(i);\r
+\r
+ return xml_node();\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str)\r
+ {\r
+ assert(str);\r
+\r
+ return impl::as_utf8_impl(str, impl::strlength_wide(str));\r
+ }\r
+\r
+ PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str)\r
+ {\r
+ return impl::as_utf8_impl(str.c_str(), str.size());\r
+ }\r
+ \r
+ PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str)\r
+ {\r
+ assert(str);\r
+\r
+ return impl::as_wide_impl(str, strlen(str));\r
+ }\r
+ \r
+ PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str)\r
+ {\r
+ return impl::as_wide_impl(str.c_str(), str.size());\r
+ }\r
+#endif\r
+\r
+ PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate)\r
+ {\r
+ impl::xml_memory::allocate = allocate;\r
+ impl::xml_memory::deallocate = deallocate;\r
+ }\r
+\r
+ PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function()\r
+ {\r
+ return impl::xml_memory::allocate;\r
+ }\r
+\r
+ PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function()\r
+ {\r
+ return impl::xml_memory::deallocate;\r
+ }\r
+}\r
+\r
+#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))\r
+namespace std\r
+{\r
+ // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)\r
+ PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+\r
+ PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+\r
+ PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+}\r
+#endif\r
+\r
+#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)\r
+namespace std\r
+{\r
+ // Workarounds for (non-standard) iterator category detection\r
+ PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+\r
+ PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+\r
+ PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&)\r
+ {\r
+ return std::bidirectional_iterator_tag();\r
+ }\r
+}\r
+#endif\r
+\r
+#ifndef PUGIXML_NO_XPATH\r
+\r
+// STL replacements\r
+PUGI__NS_BEGIN\r
+ struct equal_to\r
+ {\r
+ template <typename T> bool operator()(const T& lhs, const T& rhs) const\r
+ {\r
+ return lhs == rhs;\r
+ }\r
+ };\r
+\r
+ struct not_equal_to\r
+ {\r
+ template <typename T> bool operator()(const T& lhs, const T& rhs) const\r
+ {\r
+ return lhs != rhs;\r
+ }\r
+ };\r
+\r
+ struct less\r
+ {\r
+ template <typename T> bool operator()(const T& lhs, const T& rhs) const\r
+ {\r
+ return lhs < rhs;\r
+ }\r
+ };\r
+\r
+ struct less_equal\r
+ {\r
+ template <typename T> bool operator()(const T& lhs, const T& rhs) const\r
+ {\r
+ return lhs <= rhs;\r
+ }\r
+ };\r
+\r
+ template <typename T> void swap(T& lhs, T& rhs)\r
+ {\r
+ T temp = lhs;\r
+ lhs = rhs;\r
+ rhs = temp;\r
+ }\r
+\r
+ template <typename I, typename Pred> I min_element(I begin, I end, const Pred& pred)\r
+ {\r
+ I result = begin;\r
+\r
+ for (I it = begin + 1; it != end; ++it)\r
+ if (pred(*it, *result))\r
+ result = it;\r
+\r
+ return result;\r
+ }\r
+\r
+ template <typename I> void reverse(I begin, I end)\r
+ {\r
+ while (end - begin > 1) swap(*begin++, *--end);\r
+ }\r
+\r
+ template <typename I> I unique(I begin, I end)\r
+ {\r
+ // fast skip head\r
+ while (end - begin > 1 && *begin != *(begin + 1)) begin++;\r
+\r
+ if (begin == end) return begin;\r
+\r
+ // last written element\r
+ I write = begin++; \r
+\r
+ // merge unique elements\r
+ while (begin != end)\r
+ {\r
+ if (*begin != *write)\r
+ *++write = *begin++;\r
+ else\r
+ begin++;\r
+ }\r
+\r
+ // past-the-end (write points to live element)\r
+ return write + 1;\r
+ }\r
+\r
+ template <typename I> void copy_backwards(I begin, I end, I target)\r
+ {\r
+ while (begin != end) *--target = *--end;\r
+ }\r
+\r
+ template <typename I, typename Pred, typename T> void insertion_sort(I begin, I end, const Pred& pred, T*)\r
+ {\r
+ assert(begin != end);\r
+\r
+ for (I it = begin + 1; it != end; ++it)\r
+ {\r
+ T val = *it;\r
+\r
+ if (pred(val, *begin))\r
+ {\r
+ // move to front\r
+ copy_backwards(begin, it, it + 1);\r
+ *begin = val;\r
+ }\r
+ else\r
+ {\r
+ I hole = it;\r
+\r
+ // move hole backwards\r
+ while (pred(val, *(hole - 1)))\r
+ {\r
+ *hole = *(hole - 1);\r
+ hole--;\r
+ }\r
+\r
+ // fill hole with element\r
+ *hole = val;\r
+ }\r
+ }\r
+ }\r
+\r
+ // std variant for elements with ==\r
+ template <typename I, typename Pred> void partition(I begin, I middle, I end, const Pred& pred, I* out_eqbeg, I* out_eqend)\r
+ {\r
+ I eqbeg = middle, eqend = middle + 1;\r
+\r
+ // expand equal range\r
+ while (eqbeg != begin && *(eqbeg - 1) == *eqbeg) --eqbeg;\r
+ while (eqend != end && *eqend == *eqbeg) ++eqend;\r
+\r
+ // process outer elements\r
+ I ltend = eqbeg, gtbeg = eqend;\r
+\r
+ for (;;)\r
+ {\r
+ // find the element from the right side that belongs to the left one\r
+ for (; gtbeg != end; ++gtbeg)\r
+ if (!pred(*eqbeg, *gtbeg))\r
+ {\r
+ if (*gtbeg == *eqbeg) swap(*gtbeg, *eqend++);\r
+ else break;\r
+ }\r
+\r
+ // find the element from the left side that belongs to the right one\r
+ for (; ltend != begin; --ltend)\r
+ if (!pred(*(ltend - 1), *eqbeg))\r
+ {\r
+ if (*eqbeg == *(ltend - 1)) swap(*(ltend - 1), *--eqbeg);\r
+ else break;\r
+ }\r
+\r
+ // scanned all elements\r
+ if (gtbeg == end && ltend == begin)\r
+ {\r
+ *out_eqbeg = eqbeg;\r
+ *out_eqend = eqend;\r
+ return;\r
+ }\r
+\r
+ // make room for elements by moving equal area\r
+ if (gtbeg == end)\r
+ {\r
+ if (--ltend != --eqbeg) swap(*ltend, *eqbeg);\r
+ swap(*eqbeg, *--eqend);\r
+ }\r
+ else if (ltend == begin)\r
+ {\r
+ if (eqend != gtbeg) swap(*eqbeg, *eqend);\r
+ ++eqend;\r
+ swap(*gtbeg++, *eqbeg++);\r
+ }\r
+ else swap(*gtbeg++, *--ltend);\r
+ }\r
+ }\r
+\r
+ template <typename I, typename Pred> void median3(I first, I middle, I last, const Pred& pred)\r
+ {\r
+ if (pred(*middle, *first)) swap(*middle, *first);\r
+ if (pred(*last, *middle)) swap(*last, *middle);\r
+ if (pred(*middle, *first)) swap(*middle, *first);\r
+ }\r
+\r
+ template <typename I, typename Pred> void median(I first, I middle, I last, const Pred& pred)\r
+ {\r
+ if (last - first <= 40)\r
+ {\r
+ // median of three for small chunks\r
+ median3(first, middle, last, pred);\r
+ }\r
+ else\r
+ {\r
+ // median of nine\r
+ size_t step = (last - first + 1) / 8;\r
+\r
+ median3(first, first + step, first + 2 * step, pred);\r
+ median3(middle - step, middle, middle + step, pred);\r
+ median3(last - 2 * step, last - step, last, pred);\r
+ median3(first + step, middle, last - step, pred);\r
+ }\r
+ }\r
+\r
+ template <typename I, typename Pred> void sort(I begin, I end, const Pred& pred)\r
+ {\r
+ // sort large chunks\r
+ while (end - begin > 32)\r
+ {\r
+ // find median element\r
+ I middle = begin + (end - begin) / 2;\r
+ median(begin, middle, end - 1, pred);\r
+\r
+ // partition in three chunks (< = >)\r
+ I eqbeg, eqend;\r
+ partition(begin, middle, end, pred, &eqbeg, &eqend);\r
+\r
+ // loop on larger half\r
+ if (eqbeg - begin > end - eqend)\r
+ {\r
+ sort(eqend, end, pred);\r
+ end = eqbeg;\r
+ }\r
+ else\r
+ {\r
+ sort(begin, eqbeg, pred);\r
+ begin = eqend;\r
+ }\r
+ }\r
+\r
+ // insertion sort small chunk\r
+ if (begin != end) insertion_sort(begin, end, pred, &*begin);\r
+ }\r
+PUGI__NS_END\r
+\r
+// Allocator used for AST and evaluation stacks\r
+PUGI__NS_BEGIN\r
+ struct xpath_memory_block\r
+ { \r
+ xpath_memory_block* next;\r
+\r
+ char data[\r
+ #ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE\r
+ PUGIXML_MEMORY_XPATH_PAGE_SIZE\r
+ #else\r
+ 4096\r
+ #endif\r
+ ];\r
+ };\r
+ \r
+ class xpath_allocator\r
+ {\r
+ xpath_memory_block* _root;\r
+ size_t _root_size;\r
+\r
+ public:\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ jmp_buf* error_handler;\r
+ #endif\r
+\r
+ xpath_allocator(xpath_memory_block* root, size_t root_size = 0): _root(root), _root_size(root_size)\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ error_handler = 0;\r
+ #endif\r
+ }\r
+ \r
+ void* allocate_nothrow(size_t size)\r
+ {\r
+ const size_t block_capacity = sizeof(_root->data);\r
+\r
+ // align size so that we're able to store pointers in subsequent blocks\r
+ size = (size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);\r
+\r
+ if (_root_size + size <= block_capacity)\r
+ {\r
+ void* buf = _root->data + _root_size;\r
+ _root_size += size;\r
+ return buf;\r
+ }\r
+ else\r
+ {\r
+ size_t block_data_size = (size > block_capacity) ? size : block_capacity;\r
+ size_t block_size = block_data_size + offsetof(xpath_memory_block, data);\r
+\r
+ xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size));\r
+ if (!block) return 0;\r
+ \r
+ block->next = _root;\r
+ \r
+ _root = block;\r
+ _root_size = size;\r
+ \r
+ return block->data;\r
+ }\r
+ }\r
+\r
+ void* allocate(size_t size)\r
+ {\r
+ void* result = allocate_nothrow(size);\r
+\r
+ if (!result)\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ assert(error_handler);\r
+ longjmp(*error_handler, 1);\r
+ #else\r
+ throw std::bad_alloc();\r
+ #endif\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ void* reallocate(void* ptr, size_t old_size, size_t new_size)\r
+ {\r
+ // align size so that we're able to store pointers in subsequent blocks\r
+ old_size = (old_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);\r
+ new_size = (new_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);\r
+\r
+ // we can only reallocate the last object\r
+ assert(ptr == 0 || static_cast<char*>(ptr) + old_size == _root->data + _root_size);\r
+\r
+ // adjust root size so that we have not allocated the object at all\r
+ bool only_object = (_root_size == old_size);\r
+\r
+ if (ptr) _root_size -= old_size;\r
+\r
+ // allocate a new version (this will obviously reuse the memory if possible)\r
+ void* result = allocate(new_size);\r
+ assert(result);\r
+\r
+ // we have a new block\r
+ if (result != ptr && ptr)\r
+ {\r
+ // copy old data\r
+ assert(new_size >= old_size);\r
+ memcpy(result, ptr, old_size);\r
+\r
+ // free the previous page if it had no other objects\r
+ if (only_object)\r
+ {\r
+ assert(_root->data == result);\r
+ assert(_root->next);\r
+\r
+ xpath_memory_block* next = _root->next->next;\r
+\r
+ if (next)\r
+ {\r
+ // deallocate the whole page, unless it was the first one\r
+ xml_memory::deallocate(_root->next);\r
+ _root->next = next;\r
+ }\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ void revert(const xpath_allocator& state)\r
+ {\r
+ // free all new pages\r
+ xpath_memory_block* cur = _root;\r
+\r
+ while (cur != state._root)\r
+ {\r
+ xpath_memory_block* next = cur->next;\r
+\r
+ xml_memory::deallocate(cur);\r
+\r
+ cur = next;\r
+ }\r
+\r
+ // restore state\r
+ _root = state._root;\r
+ _root_size = state._root_size;\r
+ }\r
+\r
+ void release()\r
+ {\r
+ xpath_memory_block* cur = _root;\r
+ assert(cur);\r
+\r
+ while (cur->next)\r
+ {\r
+ xpath_memory_block* next = cur->next;\r
+\r
+ xml_memory::deallocate(cur);\r
+\r
+ cur = next;\r
+ }\r
+ }\r
+ };\r
+\r
+ struct xpath_allocator_capture\r
+ {\r
+ xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc)\r
+ {\r
+ }\r
+\r
+ ~xpath_allocator_capture()\r
+ {\r
+ _target->revert(_state);\r
+ }\r
+\r
+ xpath_allocator* _target;\r
+ xpath_allocator _state;\r
+ };\r
+\r
+ struct xpath_stack\r
+ {\r
+ xpath_allocator* result;\r
+ xpath_allocator* temp;\r
+ };\r
+\r
+ struct xpath_stack_data\r
+ {\r
+ xpath_memory_block blocks[2];\r
+ xpath_allocator result;\r
+ xpath_allocator temp;\r
+ xpath_stack stack;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ jmp_buf error_handler;\r
+ #endif\r
+\r
+ xpath_stack_data(): result(blocks + 0), temp(blocks + 1)\r
+ {\r
+ blocks[0].next = blocks[1].next = 0;\r
+\r
+ stack.result = &result;\r
+ stack.temp = &temp;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ result.error_handler = temp.error_handler = &error_handler;\r
+ #endif\r
+ }\r
+\r
+ ~xpath_stack_data()\r
+ {\r
+ result.release();\r
+ temp.release();\r
+ }\r
+ };\r
+PUGI__NS_END\r
+\r
+// String class\r
+PUGI__NS_BEGIN\r
+ class xpath_string\r
+ {\r
+ const char_t* _buffer;\r
+ bool _uses_heap;\r
+\r
+ static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc)\r
+ {\r
+ char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t)));\r
+ assert(result);\r
+\r
+ memcpy(result, string, length * sizeof(char_t));\r
+ result[length] = 0;\r
+\r
+ return result;\r
+ }\r
+\r
+ static char_t* duplicate_string(const char_t* string, xpath_allocator* alloc)\r
+ {\r
+ return duplicate_string(string, strlength(string), alloc);\r
+ }\r
+\r
+ public:\r
+ xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false)\r
+ {\r
+ }\r
+\r
+ explicit xpath_string(const char_t* str, xpath_allocator* alloc)\r
+ {\r
+ bool empty_ = (*str == 0);\r
+\r
+ _buffer = empty_ ? PUGIXML_TEXT("") : duplicate_string(str, alloc);\r
+ _uses_heap = !empty_;\r
+ }\r
+\r
+ explicit xpath_string(const char_t* str, bool use_heap): _buffer(str), _uses_heap(use_heap)\r
+ {\r
+ }\r
+\r
+ xpath_string(const char_t* begin, const char_t* end, xpath_allocator* alloc)\r
+ {\r
+ assert(begin <= end);\r
+\r
+ bool empty_ = (begin == end);\r
+\r
+ _buffer = empty_ ? PUGIXML_TEXT("") : duplicate_string(begin, static_cast<size_t>(end - begin), alloc);\r
+ _uses_heap = !empty_;\r
+ }\r
+\r
+ void append(const xpath_string& o, xpath_allocator* alloc)\r
+ {\r
+ // skip empty sources\r
+ if (!*o._buffer) return;\r
+\r
+ // fast append for constant empty target and constant source\r
+ if (!*_buffer && !_uses_heap && !o._uses_heap)\r
+ {\r
+ _buffer = o._buffer;\r
+ }\r
+ else\r
+ {\r
+ // need to make heap copy\r
+ size_t target_length = strlength(_buffer);\r
+ size_t source_length = strlength(o._buffer);\r
+ size_t result_length = target_length + source_length;\r
+\r
+ // allocate new buffer\r
+ char_t* result = static_cast<char_t*>(alloc->reallocate(_uses_heap ? const_cast<char_t*>(_buffer) : 0, (target_length + 1) * sizeof(char_t), (result_length + 1) * sizeof(char_t)));\r
+ assert(result);\r
+\r
+ // append first string to the new buffer in case there was no reallocation\r
+ if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t));\r
+\r
+ // append second string to the new buffer\r
+ memcpy(result + target_length, o._buffer, source_length * sizeof(char_t));\r
+ result[result_length] = 0;\r
+\r
+ // finalize\r
+ _buffer = result;\r
+ _uses_heap = true;\r
+ }\r
+ }\r
+\r
+ const char_t* c_str() const\r
+ {\r
+ return _buffer;\r
+ }\r
+\r
+ size_t length() const\r
+ {\r
+ return strlength(_buffer);\r
+ }\r
+ \r
+ char_t* data(xpath_allocator* alloc)\r
+ {\r
+ // make private heap copy\r
+ if (!_uses_heap)\r
+ {\r
+ _buffer = duplicate_string(_buffer, alloc);\r
+ _uses_heap = true;\r
+ }\r
+\r
+ return const_cast<char_t*>(_buffer);\r
+ }\r
+\r
+ bool empty() const\r
+ {\r
+ return *_buffer == 0;\r
+ }\r
+\r
+ bool operator==(const xpath_string& o) const\r
+ {\r
+ return strequal(_buffer, o._buffer);\r
+ }\r
+\r
+ bool operator!=(const xpath_string& o) const\r
+ {\r
+ return !strequal(_buffer, o._buffer);\r
+ }\r
+\r
+ bool uses_heap() const\r
+ {\r
+ return _uses_heap;\r
+ }\r
+ };\r
+\r
+ PUGI__FN xpath_string xpath_string_const(const char_t* str)\r
+ {\r
+ return xpath_string(str, false);\r
+ }\r
+PUGI__NS_END\r
+\r
+PUGI__NS_BEGIN\r
+ PUGI__FN bool starts_with(const char_t* string, const char_t* pattern)\r
+ {\r
+ while (*pattern && *string == *pattern)\r
+ {\r
+ string++;\r
+ pattern++;\r
+ }\r
+\r
+ return *pattern == 0;\r
+ }\r
+\r
+ PUGI__FN const char_t* find_char(const char_t* s, char_t c)\r
+ {\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcschr(s, c);\r
+ #else\r
+ return strchr(s, c);\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p)\r
+ {\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ // MSVC6 wcsstr bug workaround (if s is empty it always returns 0)\r
+ return (*p == 0) ? s : wcsstr(s, p);\r
+ #else\r
+ return strstr(s, p);\r
+ #endif\r
+ }\r
+\r
+ // Converts symbol to lower case, if it is an ASCII one\r
+ PUGI__FN char_t tolower_ascii(char_t ch)\r
+ {\r
+ return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch;\r
+ }\r
+\r
+ PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc)\r
+ {\r
+ if (na.attribute())\r
+ return xpath_string_const(na.attribute().value());\r
+ else\r
+ {\r
+ const xml_node& n = na.node();\r
+\r
+ switch (n.type())\r
+ {\r
+ case node_pcdata:\r
+ case node_cdata:\r
+ case node_comment:\r
+ case node_pi:\r
+ return xpath_string_const(n.value());\r
+ \r
+ case node_document:\r
+ case node_element:\r
+ {\r
+ xpath_string result;\r
+\r
+ xml_node cur = n.first_child();\r
+ \r
+ while (cur && cur != n)\r
+ {\r
+ if (cur.type() == node_pcdata || cur.type() == node_cdata)\r
+ result.append(xpath_string_const(cur.value()), alloc);\r
+\r
+ if (cur.first_child())\r
+ cur = cur.first_child();\r
+ else if (cur.next_sibling())\r
+ cur = cur.next_sibling();\r
+ else\r
+ {\r
+ while (!cur.next_sibling() && cur != n)\r
+ cur = cur.parent();\r
+\r
+ if (cur != n) cur = cur.next_sibling();\r
+ }\r
+ }\r
+ \r
+ return result;\r
+ }\r
+ \r
+ default:\r
+ return xpath_string();\r
+ }\r
+ }\r
+ }\r
+ \r
+ PUGI__FN unsigned int node_height(xml_node n)\r
+ {\r
+ unsigned int result = 0;\r
+ \r
+ while (n)\r
+ {\r
+ ++result;\r
+ n = n.parent();\r
+ }\r
+ \r
+ return result;\r
+ }\r
+ \r
+ PUGI__FN bool node_is_before(xml_node ln, unsigned int lh, xml_node rn, unsigned int rh)\r
+ {\r
+ // normalize heights\r
+ for (unsigned int i = rh; i < lh; i++) ln = ln.parent();\r
+ for (unsigned int j = lh; j < rh; j++) rn = rn.parent();\r
+ \r
+ // one node is the ancestor of the other\r
+ if (ln == rn) return lh < rh;\r
+ \r
+ // find common ancestor\r
+ while (ln.parent() != rn.parent())\r
+ {\r
+ ln = ln.parent();\r
+ rn = rn.parent();\r
+ }\r
+\r
+ // there is no common ancestor (the shared parent is null), nodes are from different documents\r
+ if (!ln.parent()) return ln < rn;\r
+\r
+ // determine sibling order\r
+ for (; ln; ln = ln.next_sibling())\r
+ if (ln == rn)\r
+ return true;\r
+ \r
+ return false;\r
+ }\r
+\r
+ PUGI__FN bool node_is_ancestor(xml_node parent, xml_node node)\r
+ {\r
+ while (node && node != parent) node = node.parent();\r
+\r
+ return parent && node == parent;\r
+ }\r
+\r
+ PUGI__FN const void* document_order(const xpath_node& xnode)\r
+ {\r
+ xml_node_struct* node = xnode.node().internal_object();\r
+\r
+ if (node)\r
+ {\r
+ if (node->name && (node->header & xml_memory_page_name_allocated_mask) == 0) return node->name;\r
+ if (node->value && (node->header & xml_memory_page_value_allocated_mask) == 0) return node->value;\r
+ return 0;\r
+ }\r
+\r
+ xml_attribute_struct* attr = xnode.attribute().internal_object();\r
+\r
+ if (attr)\r
+ {\r
+ if ((attr->header & xml_memory_page_name_allocated_mask) == 0) return attr->name;\r
+ if ((attr->header & xml_memory_page_value_allocated_mask) == 0) return attr->value;\r
+ return 0;\r
+ }\r
+\r
+ return 0;\r
+ }\r
+ \r
+ struct document_order_comparator\r
+ {\r
+ bool operator()(const xpath_node& lhs, const xpath_node& rhs) const\r
+ {\r
+ // optimized document order based check\r
+ const void* lo = document_order(lhs);\r
+ const void* ro = document_order(rhs);\r
+\r
+ if (lo && ro) return lo < ro;\r
+\r
+ // slow comparison\r
+ xml_node ln = lhs.node(), rn = rhs.node();\r
+\r
+ // compare attributes\r
+ if (lhs.attribute() && rhs.attribute())\r
+ {\r
+ // shared parent\r
+ if (lhs.parent() == rhs.parent())\r
+ {\r
+ // determine sibling order\r
+ for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute())\r
+ if (a == rhs.attribute())\r
+ return true;\r
+ \r
+ return false;\r
+ }\r
+ \r
+ // compare attribute parents\r
+ ln = lhs.parent();\r
+ rn = rhs.parent();\r
+ }\r
+ else if (lhs.attribute())\r
+ {\r
+ // attributes go after the parent element\r
+ if (lhs.parent() == rhs.node()) return false;\r
+ \r
+ ln = lhs.parent();\r
+ }\r
+ else if (rhs.attribute())\r
+ {\r
+ // attributes go after the parent element\r
+ if (rhs.parent() == lhs.node()) return true;\r
+ \r
+ rn = rhs.parent();\r
+ }\r
+\r
+ if (ln == rn) return false;\r
+ \r
+ unsigned int lh = node_height(ln);\r
+ unsigned int rh = node_height(rn);\r
+ \r
+ return node_is_before(ln, lh, rn, rh);\r
+ }\r
+ };\r
+\r
+ struct duplicate_comparator\r
+ {\r
+ bool operator()(const xpath_node& lhs, const xpath_node& rhs) const\r
+ {\r
+ if (lhs.attribute()) return rhs.attribute() ? lhs.attribute() < rhs.attribute() : true;\r
+ else return rhs.attribute() ? false : lhs.node() < rhs.node();\r
+ }\r
+ };\r
+ \r
+ PUGI__FN double gen_nan()\r
+ {\r
+ #if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24))\r
+ union { float f; uint32_t i; } u[sizeof(float) == sizeof(uint32_t) ? 1 : -1];\r
+ u[0].i = 0x7fc00000;\r
+ return u[0].f;\r
+ #else\r
+ // fallback\r
+ const volatile double zero = 0.0;\r
+ return zero / zero;\r
+ #endif\r
+ }\r
+ \r
+ PUGI__FN bool is_nan(double value)\r
+ {\r
+ #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)\r
+ return !!_isnan(value);\r
+ #elif defined(fpclassify) && defined(FP_NAN)\r
+ return fpclassify(value) == FP_NAN;\r
+ #else\r
+ // fallback\r
+ const volatile double v = value;\r
+ return v != v;\r
+ #endif\r
+ }\r
+ \r
+ PUGI__FN const char_t* convert_number_to_string_special(double value)\r
+ {\r
+ #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)\r
+ if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;\r
+ if (_isnan(value)) return PUGIXML_TEXT("NaN");\r
+ return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");\r
+ #elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO)\r
+ switch (fpclassify(value))\r
+ {\r
+ case FP_NAN:\r
+ return PUGIXML_TEXT("NaN");\r
+\r
+ case FP_INFINITE:\r
+ return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");\r
+\r
+ case FP_ZERO:\r
+ return PUGIXML_TEXT("0");\r
+\r
+ default:\r
+ return 0;\r
+ }\r
+ #else\r
+ // fallback\r
+ const volatile double v = value;\r
+\r
+ if (v == 0) return PUGIXML_TEXT("0");\r
+ if (v != v) return PUGIXML_TEXT("NaN");\r
+ if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");\r
+ return 0;\r
+ #endif\r
+ }\r
+ \r
+ PUGI__FN bool convert_number_to_boolean(double value)\r
+ {\r
+ return (value != 0 && !is_nan(value));\r
+ }\r
+ \r
+ PUGI__FN void truncate_zeros(char* begin, char* end)\r
+ {\r
+ while (begin != end && end[-1] == '0') end--;\r
+\r
+ *end = 0;\r
+ }\r
+\r
+ // gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent\r
+#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)\r
+ PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)\r
+ {\r
+ // get base values\r
+ int sign, exponent;\r
+ _ecvt_s(buffer, buffer_size, value, DBL_DIG + 1, &exponent, &sign);\r
+\r
+ // truncate redundant zeros\r
+ truncate_zeros(buffer, buffer + strlen(buffer));\r
+\r
+ // fill results\r
+ *out_mantissa = buffer;\r
+ *out_exponent = exponent;\r
+ }\r
+#else\r
+ PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)\r
+ {\r
+ // get a scientific notation value with IEEE DBL_DIG decimals\r
+ sprintf(buffer, "%.*e", DBL_DIG, value);\r
+ assert(strlen(buffer) < buffer_size);\r
+ (void)!buffer_size;\r
+\r
+ // get the exponent (possibly negative)\r
+ char* exponent_string = strchr(buffer, 'e');\r
+ assert(exponent_string);\r
+\r
+ int exponent = atoi(exponent_string + 1);\r
+\r
+ // extract mantissa string: skip sign\r
+ char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer;\r
+ assert(mantissa[0] != '0' && mantissa[1] == '.');\r
+\r
+ // divide mantissa by 10 to eliminate integer part\r
+ mantissa[1] = mantissa[0];\r
+ mantissa++;\r
+ exponent++;\r
+\r
+ // remove extra mantissa digits and zero-terminate mantissa\r
+ truncate_zeros(mantissa, exponent_string);\r
+\r
+ // fill results\r
+ *out_mantissa = mantissa;\r
+ *out_exponent = exponent;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc)\r
+ {\r
+ // try special number conversion\r
+ const char_t* special = convert_number_to_string_special(value);\r
+ if (special) return xpath_string_const(special);\r
+\r
+ // get mantissa + exponent form\r
+ char mantissa_buffer[32];\r
+\r
+ char* mantissa;\r
+ int exponent;\r
+ convert_number_to_mantissa_exponent(value, mantissa_buffer, sizeof(mantissa_buffer), &mantissa, &exponent);\r
+\r
+ // allocate a buffer of suitable length for the number\r
+ size_t result_size = strlen(mantissa_buffer) + (exponent > 0 ? exponent : -exponent) + 4;\r
+ char_t* result = static_cast<char_t*>(alloc->allocate(sizeof(char_t) * result_size));\r
+ assert(result);\r
+\r
+ // make the number!\r
+ char_t* s = result;\r
+\r
+ // sign\r
+ if (value < 0) *s++ = '-';\r
+\r
+ // integer part\r
+ if (exponent <= 0)\r
+ {\r
+ *s++ = '0';\r
+ }\r
+ else\r
+ {\r
+ while (exponent > 0)\r
+ {\r
+ assert(*mantissa == 0 || static_cast<unsigned int>(static_cast<unsigned int>(*mantissa) - '0') <= 9);\r
+ *s++ = *mantissa ? *mantissa++ : '0';\r
+ exponent--;\r
+ }\r
+ }\r
+\r
+ // fractional part\r
+ if (*mantissa)\r
+ {\r
+ // decimal point\r
+ *s++ = '.';\r
+\r
+ // extra zeroes from negative exponent\r
+ while (exponent < 0)\r
+ {\r
+ *s++ = '0';\r
+ exponent++;\r
+ }\r
+\r
+ // extra mantissa digits\r
+ while (*mantissa)\r
+ {\r
+ assert(static_cast<unsigned int>(*mantissa - '0') <= 9);\r
+ *s++ = *mantissa++;\r
+ }\r
+ }\r
+\r
+ // zero-terminate\r
+ assert(s < result + result_size);\r
+ *s = 0;\r
+\r
+ return xpath_string(result, true);\r
+ }\r
+ \r
+ PUGI__FN bool check_string_to_number_format(const char_t* string)\r
+ {\r
+ // parse leading whitespace\r
+ while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;\r
+\r
+ // parse sign\r
+ if (*string == '-') ++string;\r
+\r
+ if (!*string) return false;\r
+\r
+ // if there is no integer part, there should be a decimal part with at least one digit\r
+ if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false;\r
+\r
+ // parse integer part\r
+ while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;\r
+\r
+ // parse decimal part\r
+ if (*string == '.')\r
+ {\r
+ ++string;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;\r
+ }\r
+\r
+ // parse trailing whitespace\r
+ while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;\r
+\r
+ return *string == 0;\r
+ }\r
+\r
+ PUGI__FN double convert_string_to_number(const char_t* string)\r
+ {\r
+ // check string format\r
+ if (!check_string_to_number_format(string)) return gen_nan();\r
+\r
+ // parse string\r
+ #ifdef PUGIXML_WCHAR_MODE\r
+ return wcstod(string, 0);\r
+ #else\r
+ return atof(string);\r
+ #endif\r
+ }\r
+\r
+ PUGI__FN bool convert_string_to_number_scratch(char_t (&buffer)[32], const char_t* begin, const char_t* end, double* out_result)\r
+ {\r
+ size_t length = static_cast<size_t>(end - begin);\r
+ char_t* scratch = buffer;\r
+\r
+ if (length >= sizeof(buffer) / sizeof(buffer[0]))\r
+ {\r
+ // need to make dummy on-heap copy\r
+ scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!scratch) return false;\r
+ }\r
+\r
+ // copy string to zero-terminated buffer and perform conversion\r
+ memcpy(scratch, begin, length * sizeof(char_t));\r
+ scratch[length] = 0;\r
+\r
+ *out_result = convert_string_to_number(scratch);\r
+\r
+ // free dummy buffer\r
+ if (scratch != buffer) xml_memory::deallocate(scratch);\r
+\r
+ return true;\r
+ }\r
+ \r
+ PUGI__FN double round_nearest(double value)\r
+ {\r
+ return floor(value + 0.5);\r
+ }\r
+\r
+ PUGI__FN double round_nearest_nzero(double value)\r
+ {\r
+ // same as round_nearest, but returns -0 for [-0.5, -0]\r
+ // ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0)\r
+ return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5);\r
+ }\r
+ \r
+ PUGI__FN const char_t* qualified_name(const xpath_node& node)\r
+ {\r
+ return node.attribute() ? node.attribute().name() : node.node().name();\r
+ }\r
+ \r
+ PUGI__FN const char_t* local_name(const xpath_node& node)\r
+ {\r
+ const char_t* name = qualified_name(node);\r
+ const char_t* p = find_char(name, ':');\r
+ \r
+ return p ? p + 1 : name;\r
+ }\r
+\r
+ struct namespace_uri_predicate\r
+ {\r
+ const char_t* prefix;\r
+ size_t prefix_length;\r
+\r
+ namespace_uri_predicate(const char_t* name)\r
+ {\r
+ const char_t* pos = find_char(name, ':');\r
+\r
+ prefix = pos ? name : 0;\r
+ prefix_length = pos ? static_cast<size_t>(pos - name) : 0;\r
+ }\r
+\r
+ bool operator()(const xml_attribute& a) const\r
+ {\r
+ const char_t* name = a.name();\r
+\r
+ if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false;\r
+\r
+ return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0;\r
+ }\r
+ };\r
+\r
+ PUGI__FN const char_t* namespace_uri(const xml_node& node)\r
+ {\r
+ namespace_uri_predicate pred = node.name();\r
+ \r
+ xml_node p = node;\r
+ \r
+ while (p)\r
+ {\r
+ xml_attribute a = p.find_attribute(pred);\r
+ \r
+ if (a) return a.value();\r
+ \r
+ p = p.parent();\r
+ }\r
+ \r
+ return PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const char_t* namespace_uri(const xml_attribute& attr, const xml_node& parent)\r
+ {\r
+ namespace_uri_predicate pred = attr.name();\r
+ \r
+ // Default namespace does not apply to attributes\r
+ if (!pred.prefix) return PUGIXML_TEXT("");\r
+ \r
+ xml_node p = parent;\r
+ \r
+ while (p)\r
+ {\r
+ xml_attribute a = p.find_attribute(pred);\r
+ \r
+ if (a) return a.value();\r
+ \r
+ p = p.parent();\r
+ }\r
+ \r
+ return PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const char_t* namespace_uri(const xpath_node& node)\r
+ {\r
+ return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node());\r
+ }\r
+\r
+ PUGI__FN void normalize_space(char_t* buffer)\r
+ {\r
+ char_t* write = buffer;\r
+\r
+ for (char_t* it = buffer; *it; )\r
+ {\r
+ char_t ch = *it++;\r
+\r
+ if (PUGI__IS_CHARTYPE(ch, ct_space))\r
+ {\r
+ // replace whitespace sequence with single space\r
+ while (PUGI__IS_CHARTYPE(*it, ct_space)) it++;\r
+\r
+ // avoid leading spaces\r
+ if (write != buffer) *write++ = ' ';\r
+ }\r
+ else *write++ = ch;\r
+ }\r
+\r
+ // remove trailing space\r
+ if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--;\r
+\r
+ // zero-terminate\r
+ *write = 0;\r
+ }\r
+\r
+ PUGI__FN void translate(char_t* buffer, const char_t* from, const char_t* to)\r
+ {\r
+ size_t to_length = strlength(to);\r
+\r
+ char_t* write = buffer;\r
+\r
+ while (*buffer)\r
+ {\r
+ PUGI__DMC_VOLATILE char_t ch = *buffer++;\r
+\r
+ const char_t* pos = find_char(from, ch);\r
+\r
+ if (!pos)\r
+ *write++ = ch; // do not process\r
+ else if (static_cast<size_t>(pos - from) < to_length)\r
+ *write++ = to[pos - from]; // replace\r
+ }\r
+\r
+ // zero-terminate\r
+ *write = 0;\r
+ }\r
+\r
+ struct xpath_variable_boolean: xpath_variable\r
+ {\r
+ xpath_variable_boolean(): value(false)\r
+ {\r
+ }\r
+\r
+ bool value;\r
+ char_t name[1];\r
+ };\r
+\r
+ struct xpath_variable_number: xpath_variable\r
+ {\r
+ xpath_variable_number(): value(0)\r
+ {\r
+ }\r
+\r
+ double value;\r
+ char_t name[1];\r
+ };\r
+\r
+ struct xpath_variable_string: xpath_variable\r
+ {\r
+ xpath_variable_string(): value(0)\r
+ {\r
+ }\r
+\r
+ ~xpath_variable_string()\r
+ {\r
+ if (value) xml_memory::deallocate(value);\r
+ }\r
+\r
+ char_t* value;\r
+ char_t name[1];\r
+ };\r
+\r
+ struct xpath_variable_node_set: xpath_variable\r
+ {\r
+ xpath_node_set value;\r
+ char_t name[1];\r
+ };\r
+\r
+ static const xpath_node_set dummy_node_set;\r
+\r
+ PUGI__FN unsigned int hash_string(const char_t* str)\r
+ {\r
+ // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)\r
+ unsigned int result = 0;\r
+\r
+ while (*str)\r
+ {\r
+ result += static_cast<unsigned int>(*str++);\r
+ result += result << 10;\r
+ result ^= result >> 6;\r
+ }\r
+ \r
+ result += result << 3;\r
+ result ^= result >> 11;\r
+ result += result << 15;\r
+ \r
+ return result;\r
+ }\r
+\r
+ template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name)\r
+ {\r
+ size_t length = strlength(name);\r
+ if (length == 0) return 0; // empty variable names are invalid\r
+\r
+ // $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters\r
+ void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t));\r
+ if (!memory) return 0;\r
+\r
+ T* result = new (memory) T();\r
+\r
+ memcpy(result->name, name, (length + 1) * sizeof(char_t));\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name)\r
+ {\r
+ switch (type)\r
+ {\r
+ case xpath_type_node_set:\r
+ return new_xpath_variable<xpath_variable_node_set>(name);\r
+\r
+ case xpath_type_number:\r
+ return new_xpath_variable<xpath_variable_number>(name);\r
+\r
+ case xpath_type_string:\r
+ return new_xpath_variable<xpath_variable_string>(name);\r
+\r
+ case xpath_type_boolean:\r
+ return new_xpath_variable<xpath_variable_boolean>(name);\r
+\r
+ default:\r
+ return 0;\r
+ }\r
+ }\r
+\r
+ template <typename T> PUGI__FN void delete_xpath_variable(T* var)\r
+ {\r
+ var->~T();\r
+ xml_memory::deallocate(var);\r
+ }\r
+\r
+ PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var)\r
+ {\r
+ switch (type)\r
+ {\r
+ case xpath_type_node_set:\r
+ delete_xpath_variable(static_cast<xpath_variable_node_set*>(var));\r
+ break;\r
+\r
+ case xpath_type_number:\r
+ delete_xpath_variable(static_cast<xpath_variable_number*>(var));\r
+ break;\r
+\r
+ case xpath_type_string:\r
+ delete_xpath_variable(static_cast<xpath_variable_string*>(var));\r
+ break;\r
+\r
+ case xpath_type_boolean:\r
+ delete_xpath_variable(static_cast<xpath_variable_boolean*>(var));\r
+ break;\r
+\r
+ default:\r
+ assert(!"Invalid variable type");\r
+ }\r
+ }\r
+\r
+ PUGI__FN xpath_variable* get_variable_scratch(char_t (&buffer)[32], xpath_variable_set* set, const char_t* begin, const char_t* end)\r
+ {\r
+ size_t length = static_cast<size_t>(end - begin);\r
+ char_t* scratch = buffer;\r
+\r
+ if (length >= sizeof(buffer) / sizeof(buffer[0]))\r
+ {\r
+ // need to make dummy on-heap copy\r
+ scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));\r
+ if (!scratch) return 0;\r
+ }\r
+\r
+ // copy string to zero-terminated buffer and perform lookup\r
+ memcpy(scratch, begin, length * sizeof(char_t));\r
+ scratch[length] = 0;\r
+\r
+ xpath_variable* result = set->get(scratch);\r
+\r
+ // free dummy buffer\r
+ if (scratch != buffer) xml_memory::deallocate(scratch);\r
+\r
+ return result;\r
+ }\r
+PUGI__NS_END\r
+\r
+// Internal node set class\r
+PUGI__NS_BEGIN\r
+ PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev)\r
+ {\r
+ xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;\r
+\r
+ if (type == xpath_node_set::type_unsorted)\r
+ {\r
+ sort(begin, end, document_order_comparator());\r
+\r
+ type = xpath_node_set::type_sorted;\r
+ }\r
+ \r
+ if (type != order) reverse(begin, end);\r
+ \r
+ return order;\r
+ }\r
+\r
+ PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type)\r
+ {\r
+ if (begin == end) return xpath_node();\r
+\r
+ switch (type)\r
+ {\r
+ case xpath_node_set::type_sorted:\r
+ return *begin;\r
+\r
+ case xpath_node_set::type_sorted_reverse:\r
+ return *(end - 1);\r
+\r
+ case xpath_node_set::type_unsorted:\r
+ return *min_element(begin, end, document_order_comparator());\r
+\r
+ default:\r
+ assert(!"Invalid node set type");\r
+ return xpath_node();\r
+ }\r
+ }\r
+\r
+ class xpath_node_set_raw\r
+ {\r
+ xpath_node_set::type_t _type;\r
+\r
+ xpath_node* _begin;\r
+ xpath_node* _end;\r
+ xpath_node* _eos;\r
+\r
+ public:\r
+ xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0)\r
+ {\r
+ }\r
+\r
+ xpath_node* begin() const\r
+ {\r
+ return _begin;\r
+ }\r
+\r
+ xpath_node* end() const\r
+ {\r
+ return _end;\r
+ }\r
+\r
+ bool empty() const\r
+ {\r
+ return _begin == _end;\r
+ }\r
+\r
+ size_t size() const\r
+ {\r
+ return static_cast<size_t>(_end - _begin);\r
+ }\r
+\r
+ xpath_node first() const\r
+ {\r
+ return xpath_first(_begin, _end, _type);\r
+ }\r
+\r
+ void push_back(const xpath_node& node, xpath_allocator* alloc)\r
+ {\r
+ if (_end == _eos)\r
+ {\r
+ size_t capacity = static_cast<size_t>(_eos - _begin);\r
+\r
+ // get new capacity (1.5x rule)\r
+ size_t new_capacity = capacity + capacity / 2 + 1;\r
+\r
+ // reallocate the old array or allocate a new one\r
+ xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node)));\r
+ assert(data);\r
+\r
+ // finalize\r
+ _begin = data;\r
+ _end = data + capacity;\r
+ _eos = data + new_capacity;\r
+ }\r
+\r
+ *_end++ = node;\r
+ }\r
+\r
+ void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc)\r
+ {\r
+ size_t size_ = static_cast<size_t>(_end - _begin);\r
+ size_t capacity = static_cast<size_t>(_eos - _begin);\r
+ size_t count = static_cast<size_t>(end_ - begin_);\r
+\r
+ if (size_ + count > capacity)\r
+ {\r
+ // reallocate the old array or allocate a new one\r
+ xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node)));\r
+ assert(data);\r
+\r
+ // finalize\r
+ _begin = data;\r
+ _end = data + size_;\r
+ _eos = data + size_ + count;\r
+ }\r
+\r
+ memcpy(_end, begin_, count * sizeof(xpath_node));\r
+ _end += count;\r
+ }\r
+\r
+ void sort_do()\r
+ {\r
+ _type = xpath_sort(_begin, _end, _type, false);\r
+ }\r
+\r
+ void truncate(xpath_node* pos)\r
+ {\r
+ assert(_begin <= pos && pos <= _end);\r
+\r
+ _end = pos;\r
+ }\r
+\r
+ void remove_duplicates()\r
+ {\r
+ if (_type == xpath_node_set::type_unsorted)\r
+ sort(_begin, _end, duplicate_comparator());\r
+ \r
+ _end = unique(_begin, _end);\r
+ }\r
+\r
+ xpath_node_set::type_t type() const\r
+ {\r
+ return _type;\r
+ }\r
+\r
+ void set_type(xpath_node_set::type_t value)\r
+ {\r
+ _type = value;\r
+ }\r
+ };\r
+PUGI__NS_END\r
+\r
+PUGI__NS_BEGIN\r
+ struct xpath_context\r
+ {\r
+ xpath_node n;\r
+ size_t position, size;\r
+\r
+ xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_)\r
+ {\r
+ }\r
+ };\r
+\r
+ enum lexeme_t\r
+ {\r
+ lex_none = 0,\r
+ lex_equal,\r
+ lex_not_equal,\r
+ lex_less,\r
+ lex_greater,\r
+ lex_less_or_equal,\r
+ lex_greater_or_equal,\r
+ lex_plus,\r
+ lex_minus,\r
+ lex_multiply,\r
+ lex_union,\r
+ lex_var_ref,\r
+ lex_open_brace,\r
+ lex_close_brace,\r
+ lex_quoted_string,\r
+ lex_number,\r
+ lex_slash,\r
+ lex_double_slash,\r
+ lex_open_square_brace,\r
+ lex_close_square_brace,\r
+ lex_string,\r
+ lex_comma,\r
+ lex_axis_attribute,\r
+ lex_dot,\r
+ lex_double_dot,\r
+ lex_double_colon,\r
+ lex_eof\r
+ };\r
+\r
+ struct xpath_lexer_string\r
+ {\r
+ const char_t* begin;\r
+ const char_t* end;\r
+\r
+ xpath_lexer_string(): begin(0), end(0)\r
+ {\r
+ }\r
+\r
+ bool operator==(const char_t* other) const\r
+ {\r
+ size_t length = static_cast<size_t>(end - begin);\r
+\r
+ return strequalrange(other, begin, length);\r
+ }\r
+ };\r
+\r
+ class xpath_lexer\r
+ {\r
+ const char_t* _cur;\r
+ const char_t* _cur_lexeme_pos;\r
+ xpath_lexer_string _cur_lexeme_contents;\r
+\r
+ lexeme_t _cur_lexeme;\r
+\r
+ public:\r
+ explicit xpath_lexer(const char_t* query): _cur(query)\r
+ {\r
+ next();\r
+ }\r
+ \r
+ const char_t* state() const\r
+ {\r
+ return _cur;\r
+ }\r
+ \r
+ void next()\r
+ {\r
+ const char_t* cur = _cur;\r
+\r
+ while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur;\r
+\r
+ // save lexeme position for error reporting\r
+ _cur_lexeme_pos = cur;\r
+\r
+ switch (*cur)\r
+ {\r
+ case 0:\r
+ _cur_lexeme = lex_eof;\r
+ break;\r
+ \r
+ case '>':\r
+ if (*(cur+1) == '=')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_greater_or_equal;\r
+ }\r
+ else\r
+ {\r
+ cur += 1;\r
+ _cur_lexeme = lex_greater;\r
+ }\r
+ break;\r
+\r
+ case '<':\r
+ if (*(cur+1) == '=')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_less_or_equal;\r
+ }\r
+ else\r
+ {\r
+ cur += 1;\r
+ _cur_lexeme = lex_less;\r
+ }\r
+ break;\r
+\r
+ case '!':\r
+ if (*(cur+1) == '=')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_not_equal;\r
+ }\r
+ else\r
+ {\r
+ _cur_lexeme = lex_none;\r
+ }\r
+ break;\r
+\r
+ case '=':\r
+ cur += 1;\r
+ _cur_lexeme = lex_equal;\r
+\r
+ break;\r
+ \r
+ case '+':\r
+ cur += 1;\r
+ _cur_lexeme = lex_plus;\r
+\r
+ break;\r
+\r
+ case '-':\r
+ cur += 1;\r
+ _cur_lexeme = lex_minus;\r
+\r
+ break;\r
+\r
+ case '*':\r
+ cur += 1;\r
+ _cur_lexeme = lex_multiply;\r
+\r
+ break;\r
+\r
+ case '|':\r
+ cur += 1;\r
+ _cur_lexeme = lex_union;\r
+\r
+ break;\r
+ \r
+ case '$':\r
+ cur += 1;\r
+\r
+ if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))\r
+ {\r
+ _cur_lexeme_contents.begin = cur;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;\r
+\r
+ if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname\r
+ {\r
+ cur++; // :\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;\r
+ }\r
+\r
+ _cur_lexeme_contents.end = cur;\r
+ \r
+ _cur_lexeme = lex_var_ref;\r
+ }\r
+ else\r
+ {\r
+ _cur_lexeme = lex_none;\r
+ }\r
+\r
+ break;\r
+\r
+ case '(':\r
+ cur += 1;\r
+ _cur_lexeme = lex_open_brace;\r
+\r
+ break;\r
+\r
+ case ')':\r
+ cur += 1;\r
+ _cur_lexeme = lex_close_brace;\r
+\r
+ break;\r
+ \r
+ case '[':\r
+ cur += 1;\r
+ _cur_lexeme = lex_open_square_brace;\r
+\r
+ break;\r
+\r
+ case ']':\r
+ cur += 1;\r
+ _cur_lexeme = lex_close_square_brace;\r
+\r
+ break;\r
+\r
+ case ',':\r
+ cur += 1;\r
+ _cur_lexeme = lex_comma;\r
+\r
+ break;\r
+\r
+ case '/':\r
+ if (*(cur+1) == '/')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_double_slash;\r
+ }\r
+ else\r
+ {\r
+ cur += 1;\r
+ _cur_lexeme = lex_slash;\r
+ }\r
+ break;\r
+ \r
+ case '.':\r
+ if (*(cur+1) == '.')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_double_dot;\r
+ }\r
+ else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit))\r
+ {\r
+ _cur_lexeme_contents.begin = cur; // .\r
+\r
+ ++cur;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;\r
+\r
+ _cur_lexeme_contents.end = cur;\r
+ \r
+ _cur_lexeme = lex_number;\r
+ }\r
+ else\r
+ {\r
+ cur += 1;\r
+ _cur_lexeme = lex_dot;\r
+ }\r
+ break;\r
+\r
+ case '@':\r
+ cur += 1;\r
+ _cur_lexeme = lex_axis_attribute;\r
+\r
+ break;\r
+\r
+ case '"':\r
+ case '\'':\r
+ {\r
+ char_t terminator = *cur;\r
+\r
+ ++cur;\r
+\r
+ _cur_lexeme_contents.begin = cur;\r
+ while (*cur && *cur != terminator) cur++;\r
+ _cur_lexeme_contents.end = cur;\r
+ \r
+ if (!*cur)\r
+ _cur_lexeme = lex_none;\r
+ else\r
+ {\r
+ cur += 1;\r
+ _cur_lexeme = lex_quoted_string;\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ case ':':\r
+ if (*(cur+1) == ':')\r
+ {\r
+ cur += 2;\r
+ _cur_lexeme = lex_double_colon;\r
+ }\r
+ else\r
+ {\r
+ _cur_lexeme = lex_none;\r
+ }\r
+ break;\r
+\r
+ default:\r
+ if (PUGI__IS_CHARTYPEX(*cur, ctx_digit))\r
+ {\r
+ _cur_lexeme_contents.begin = cur;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;\r
+ \r
+ if (*cur == '.')\r
+ {\r
+ cur++;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;\r
+ }\r
+\r
+ _cur_lexeme_contents.end = cur;\r
+\r
+ _cur_lexeme = lex_number;\r
+ }\r
+ else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))\r
+ {\r
+ _cur_lexeme_contents.begin = cur;\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;\r
+\r
+ if (cur[0] == ':')\r
+ {\r
+ if (cur[1] == '*') // namespace test ncname:*\r
+ {\r
+ cur += 2; // :*\r
+ }\r
+ else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname\r
+ {\r
+ cur++; // :\r
+\r
+ while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;\r
+ }\r
+ }\r
+\r
+ _cur_lexeme_contents.end = cur;\r
+ \r
+ _cur_lexeme = lex_string;\r
+ }\r
+ else\r
+ {\r
+ _cur_lexeme = lex_none;\r
+ }\r
+ }\r
+\r
+ _cur = cur;\r
+ }\r
+\r
+ lexeme_t current() const\r
+ {\r
+ return _cur_lexeme;\r
+ }\r
+\r
+ const char_t* current_pos() const\r
+ {\r
+ return _cur_lexeme_pos;\r
+ }\r
+\r
+ const xpath_lexer_string& contents() const\r
+ {\r
+ assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string);\r
+\r
+ return _cur_lexeme_contents;\r
+ }\r
+ };\r
+\r
+ enum ast_type_t\r
+ {\r
+ ast_unknown,\r
+ ast_op_or, // left or right\r
+ ast_op_and, // left and right\r
+ ast_op_equal, // left = right\r
+ ast_op_not_equal, // left != right\r
+ ast_op_less, // left < right\r
+ ast_op_greater, // left > right\r
+ ast_op_less_or_equal, // left <= right\r
+ ast_op_greater_or_equal, // left >= right\r
+ ast_op_add, // left + right\r
+ ast_op_subtract, // left - right\r
+ ast_op_multiply, // left * right\r
+ ast_op_divide, // left / right\r
+ ast_op_mod, // left % right\r
+ ast_op_negate, // left - right\r
+ ast_op_union, // left | right\r
+ ast_predicate, // apply predicate to set; next points to next predicate\r
+ ast_filter, // select * from left where right\r
+ ast_filter_posinv, // select * from left where right; proximity position invariant\r
+ ast_string_constant, // string constant\r
+ ast_number_constant, // number constant\r
+ ast_variable, // variable\r
+ ast_func_last, // last()\r
+ ast_func_position, // position()\r
+ ast_func_count, // count(left)\r
+ ast_func_id, // id(left)\r
+ ast_func_local_name_0, // local-name()\r
+ ast_func_local_name_1, // local-name(left)\r
+ ast_func_namespace_uri_0, // namespace-uri()\r
+ ast_func_namespace_uri_1, // namespace-uri(left)\r
+ ast_func_name_0, // name()\r
+ ast_func_name_1, // name(left)\r
+ ast_func_string_0, // string()\r
+ ast_func_string_1, // string(left)\r
+ ast_func_concat, // concat(left, right, siblings)\r
+ ast_func_starts_with, // starts_with(left, right)\r
+ ast_func_contains, // contains(left, right)\r
+ ast_func_substring_before, // substring-before(left, right)\r
+ ast_func_substring_after, // substring-after(left, right)\r
+ ast_func_substring_2, // substring(left, right)\r
+ ast_func_substring_3, // substring(left, right, third)\r
+ ast_func_string_length_0, // string-length()\r
+ ast_func_string_length_1, // string-length(left)\r
+ ast_func_normalize_space_0, // normalize-space()\r
+ ast_func_normalize_space_1, // normalize-space(left)\r
+ ast_func_translate, // translate(left, right, third)\r
+ ast_func_boolean, // boolean(left)\r
+ ast_func_not, // not(left)\r
+ ast_func_true, // true()\r
+ ast_func_false, // false()\r
+ ast_func_lang, // lang(left)\r
+ ast_func_number_0, // number()\r
+ ast_func_number_1, // number(left)\r
+ ast_func_sum, // sum(left)\r
+ ast_func_floor, // floor(left)\r
+ ast_func_ceiling, // ceiling(left)\r
+ ast_func_round, // round(left)\r
+ ast_step, // process set left with step\r
+ ast_step_root // select root node\r
+ };\r
+\r
+ enum axis_t\r
+ {\r
+ axis_ancestor,\r
+ axis_ancestor_or_self,\r
+ axis_attribute,\r
+ axis_child,\r
+ axis_descendant,\r
+ axis_descendant_or_self,\r
+ axis_following,\r
+ axis_following_sibling,\r
+ axis_namespace,\r
+ axis_parent,\r
+ axis_preceding,\r
+ axis_preceding_sibling,\r
+ axis_self\r
+ };\r
+ \r
+ enum nodetest_t\r
+ {\r
+ nodetest_none,\r
+ nodetest_name,\r
+ nodetest_type_node,\r
+ nodetest_type_comment,\r
+ nodetest_type_pi,\r
+ nodetest_type_text,\r
+ nodetest_pi,\r
+ nodetest_all,\r
+ nodetest_all_in_namespace\r
+ };\r
+\r
+ template <axis_t N> struct axis_to_type\r
+ {\r
+ static const axis_t axis;\r
+ };\r
+\r
+ template <axis_t N> const axis_t axis_to_type<N>::axis = N;\r
+ \r
+ class xpath_ast_node\r
+ {\r
+ private:\r
+ // node type\r
+ char _type;\r
+ char _rettype;\r
+\r
+ // for ast_step / ast_predicate\r
+ char _axis;\r
+ char _test;\r
+\r
+ // tree node structure\r
+ xpath_ast_node* _left;\r
+ xpath_ast_node* _right;\r
+ xpath_ast_node* _next;\r
+\r
+ union\r
+ {\r
+ // value for ast_string_constant\r
+ const char_t* string;\r
+ // value for ast_number_constant\r
+ double number;\r
+ // variable for ast_variable\r
+ xpath_variable* variable;\r
+ // node test for ast_step (node name/namespace/node type/pi target)\r
+ const char_t* nodetest;\r
+ } _data;\r
+\r
+ xpath_ast_node(const xpath_ast_node&);\r
+ xpath_ast_node& operator=(const xpath_ast_node&);\r
+\r
+ template <class Comp> static bool compare_eq(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)\r
+ {\r
+ xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();\r
+\r
+ if (lt != xpath_type_node_set && rt != xpath_type_node_set)\r
+ {\r
+ if (lt == xpath_type_boolean || rt == xpath_type_boolean)\r
+ return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));\r
+ else if (lt == xpath_type_number || rt == xpath_type_number)\r
+ return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));\r
+ else if (lt == xpath_type_string || rt == xpath_type_string)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_string ls = lhs->eval_string(c, stack);\r
+ xpath_string rs = rhs->eval_string(c, stack);\r
+\r
+ return comp(ls, rs);\r
+ }\r
+ }\r
+ else if (lt == xpath_type_node_set && rt == xpath_type_node_set)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ls = lhs->eval_node_set(c, stack);\r
+ xpath_node_set_raw rs = rhs->eval_node_set(c, stack);\r
+\r
+ for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)\r
+ for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ if (comp(string_value(*li, stack.result), string_value(*ri, stack.result)))\r
+ return true;\r
+ }\r
+\r
+ return false;\r
+ }\r
+ else\r
+ {\r
+ if (lt == xpath_type_node_set)\r
+ {\r
+ swap(lhs, rhs);\r
+ swap(lt, rt);\r
+ }\r
+\r
+ if (lt == xpath_type_boolean)\r
+ return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));\r
+ else if (lt == xpath_type_number)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ double l = lhs->eval_number(c, stack);\r
+ xpath_node_set_raw rs = rhs->eval_node_set(c, stack);\r
+\r
+ for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))\r
+ return true;\r
+ }\r
+\r
+ return false;\r
+ }\r
+ else if (lt == xpath_type_string)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_string l = lhs->eval_string(c, stack);\r
+ xpath_node_set_raw rs = rhs->eval_node_set(c, stack);\r
+\r
+ for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ if (comp(l, string_value(*ri, stack.result)))\r
+ return true;\r
+ }\r
+\r
+ return false;\r
+ }\r
+ }\r
+\r
+ assert(!"Wrong types");\r
+ return false;\r
+ }\r
+\r
+ template <class Comp> static bool compare_rel(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)\r
+ {\r
+ xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();\r
+\r
+ if (lt != xpath_type_node_set && rt != xpath_type_node_set)\r
+ return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));\r
+ else if (lt == xpath_type_node_set && rt == xpath_type_node_set)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ls = lhs->eval_node_set(c, stack);\r
+ xpath_node_set_raw rs = rhs->eval_node_set(c, stack);\r
+\r
+ for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ double l = convert_string_to_number(string_value(*li, stack.result).c_str());\r
+\r
+ for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)\r
+ {\r
+ xpath_allocator_capture crii(stack.result);\r
+\r
+ if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))\r
+ return true;\r
+ }\r
+ }\r
+\r
+ return false;\r
+ }\r
+ else if (lt != xpath_type_node_set && rt == xpath_type_node_set)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ double l = lhs->eval_number(c, stack);\r
+ xpath_node_set_raw rs = rhs->eval_node_set(c, stack);\r
+\r
+ for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))\r
+ return true;\r
+ }\r
+\r
+ return false;\r
+ }\r
+ else if (lt == xpath_type_node_set && rt != xpath_type_node_set)\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ls = lhs->eval_node_set(c, stack);\r
+ double r = rhs->eval_number(c, stack);\r
+\r
+ for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r))\r
+ return true;\r
+ }\r
+\r
+ return false;\r
+ }\r
+ else\r
+ {\r
+ assert(!"Wrong types");\r
+ return false;\r
+ }\r
+ }\r
+\r
+ void apply_predicate(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack)\r
+ {\r
+ assert(ns.size() >= first);\r
+\r
+ size_t i = 1;\r
+ size_t size = ns.size() - first;\r
+ \r
+ xpath_node* last = ns.begin() + first;\r
+ \r
+ // remove_if... or well, sort of\r
+ for (xpath_node* it = last; it != ns.end(); ++it, ++i)\r
+ {\r
+ xpath_context c(*it, i, size);\r
+ \r
+ if (expr->rettype() == xpath_type_number)\r
+ {\r
+ if (expr->eval_number(c, stack) == i)\r
+ *last++ = *it;\r
+ }\r
+ else if (expr->eval_boolean(c, stack))\r
+ *last++ = *it;\r
+ }\r
+ \r
+ ns.truncate(last);\r
+ }\r
+\r
+ void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack)\r
+ {\r
+ if (ns.size() == first) return;\r
+ \r
+ for (xpath_ast_node* pred = _right; pred; pred = pred->_next)\r
+ {\r
+ apply_predicate(ns, first, pred->_left, stack);\r
+ }\r
+ }\r
+\r
+ void step_push(xpath_node_set_raw& ns, const xml_attribute& a, const xml_node& parent, xpath_allocator* alloc)\r
+ {\r
+ if (!a) return;\r
+\r
+ const char_t* name = a.name();\r
+\r
+ // There are no attribute nodes corresponding to attributes that declare namespaces\r
+ // That is, "xmlns:..." or "xmlns"\r
+ if (starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':')) return;\r
+ \r
+ switch (_test)\r
+ {\r
+ case nodetest_name:\r
+ if (strequal(name, _data.nodetest)) ns.push_back(xpath_node(a, parent), alloc);\r
+ break;\r
+ \r
+ case nodetest_type_node:\r
+ case nodetest_all:\r
+ ns.push_back(xpath_node(a, parent), alloc);\r
+ break;\r
+ \r
+ case nodetest_all_in_namespace:\r
+ if (starts_with(name, _data.nodetest))\r
+ ns.push_back(xpath_node(a, parent), alloc);\r
+ break;\r
+ \r
+ default:\r
+ ;\r
+ }\r
+ }\r
+ \r
+ void step_push(xpath_node_set_raw& ns, const xml_node& n, xpath_allocator* alloc)\r
+ {\r
+ if (!n) return;\r
+\r
+ switch (_test)\r
+ {\r
+ case nodetest_name:\r
+ if (n.type() == node_element && strequal(n.name(), _data.nodetest)) ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_type_node:\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_type_comment:\r
+ if (n.type() == node_comment)\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_type_text:\r
+ if (n.type() == node_pcdata || n.type() == node_cdata)\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_type_pi:\r
+ if (n.type() == node_pi)\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_pi:\r
+ if (n.type() == node_pi && strequal(n.name(), _data.nodetest))\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_all:\r
+ if (n.type() == node_element)\r
+ ns.push_back(n, alloc);\r
+ break;\r
+ \r
+ case nodetest_all_in_namespace:\r
+ if (n.type() == node_element && starts_with(n.name(), _data.nodetest))\r
+ ns.push_back(n, alloc);\r
+ break;\r
+\r
+ default:\r
+ assert(!"Unknown axis");\r
+ } \r
+ }\r
+\r
+ template <class T> void step_fill(xpath_node_set_raw& ns, const xml_node& n, xpath_allocator* alloc, T)\r
+ {\r
+ const axis_t axis = T::axis;\r
+\r
+ switch (axis)\r
+ {\r
+ case axis_attribute:\r
+ {\r
+ for (xml_attribute a = n.first_attribute(); a; a = a.next_attribute())\r
+ step_push(ns, a, n, alloc);\r
+ \r
+ break;\r
+ }\r
+ \r
+ case axis_child:\r
+ {\r
+ for (xml_node c = n.first_child(); c; c = c.next_sibling())\r
+ step_push(ns, c, alloc);\r
+ \r
+ break;\r
+ }\r
+ \r
+ case axis_descendant:\r
+ case axis_descendant_or_self:\r
+ {\r
+ if (axis == axis_descendant_or_self)\r
+ step_push(ns, n, alloc);\r
+ \r
+ xml_node cur = n.first_child();\r
+ \r
+ while (cur && cur != n)\r
+ {\r
+ step_push(ns, cur, alloc);\r
+ \r
+ if (cur.first_child())\r
+ cur = cur.first_child();\r
+ else if (cur.next_sibling())\r
+ cur = cur.next_sibling();\r
+ else\r
+ {\r
+ while (!cur.next_sibling() && cur != n)\r
+ cur = cur.parent();\r
+ \r
+ if (cur != n) cur = cur.next_sibling();\r
+ }\r
+ }\r
+ \r
+ break;\r
+ }\r
+ \r
+ case axis_following_sibling:\r
+ {\r
+ for (xml_node c = n.next_sibling(); c; c = c.next_sibling())\r
+ step_push(ns, c, alloc);\r
+ \r
+ break;\r
+ }\r
+ \r
+ case axis_preceding_sibling:\r
+ {\r
+ for (xml_node c = n.previous_sibling(); c; c = c.previous_sibling())\r
+ step_push(ns, c, alloc);\r
+ \r
+ break;\r
+ }\r
+ \r
+ case axis_following:\r
+ {\r
+ xml_node cur = n;\r
+\r
+ // exit from this node so that we don't include descendants\r
+ while (cur && !cur.next_sibling()) cur = cur.parent();\r
+ cur = cur.next_sibling();\r
+\r
+ for (;;)\r
+ {\r
+ step_push(ns, cur, alloc);\r
+\r
+ if (cur.first_child())\r
+ cur = cur.first_child();\r
+ else if (cur.next_sibling())\r
+ cur = cur.next_sibling();\r
+ else\r
+ {\r
+ while (cur && !cur.next_sibling()) cur = cur.parent();\r
+ cur = cur.next_sibling();\r
+\r
+ if (!cur) break;\r
+ }\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ case axis_preceding:\r
+ {\r
+ xml_node cur = n;\r
+\r
+ while (cur && !cur.previous_sibling()) cur = cur.parent();\r
+ cur = cur.previous_sibling();\r
+\r
+ for (;;)\r
+ {\r
+ if (cur.last_child())\r
+ cur = cur.last_child();\r
+ else\r
+ {\r
+ // leaf node, can't be ancestor\r
+ step_push(ns, cur, alloc);\r
+\r
+ if (cur.previous_sibling())\r
+ cur = cur.previous_sibling();\r
+ else\r
+ {\r
+ do \r
+ {\r
+ cur = cur.parent();\r
+ if (!cur) break;\r
+\r
+ if (!node_is_ancestor(cur, n)) step_push(ns, cur, alloc);\r
+ }\r
+ while (!cur.previous_sibling());\r
+\r
+ cur = cur.previous_sibling();\r
+\r
+ if (!cur) break;\r
+ }\r
+ }\r
+ }\r
+\r
+ break;\r
+ }\r
+ \r
+ case axis_ancestor:\r
+ case axis_ancestor_or_self:\r
+ {\r
+ if (axis == axis_ancestor_or_self)\r
+ step_push(ns, n, alloc);\r
+\r
+ xml_node cur = n.parent();\r
+ \r
+ while (cur)\r
+ {\r
+ step_push(ns, cur, alloc);\r
+ \r
+ cur = cur.parent();\r
+ }\r
+ \r
+ break;\r
+ }\r
+\r
+ case axis_self:\r
+ {\r
+ step_push(ns, n, alloc);\r
+\r
+ break;\r
+ }\r
+\r
+ case axis_parent:\r
+ {\r
+ if (n.parent()) step_push(ns, n.parent(), alloc);\r
+\r
+ break;\r
+ }\r
+ \r
+ default:\r
+ assert(!"Unimplemented axis");\r
+ }\r
+ }\r
+ \r
+ template <class T> void step_fill(xpath_node_set_raw& ns, const xml_attribute& a, const xml_node& p, xpath_allocator* alloc, T v)\r
+ {\r
+ const axis_t axis = T::axis;\r
+\r
+ switch (axis)\r
+ {\r
+ case axis_ancestor:\r
+ case axis_ancestor_or_self:\r
+ {\r
+ if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test\r
+ step_push(ns, a, p, alloc);\r
+\r
+ xml_node cur = p;\r
+ \r
+ while (cur)\r
+ {\r
+ step_push(ns, cur, alloc);\r
+ \r
+ cur = cur.parent();\r
+ }\r
+ \r
+ break;\r
+ }\r
+\r
+ case axis_descendant_or_self:\r
+ case axis_self:\r
+ {\r
+ if (_test == nodetest_type_node) // reject attributes based on principal node type test\r
+ step_push(ns, a, p, alloc);\r
+\r
+ break;\r
+ }\r
+\r
+ case axis_following:\r
+ {\r
+ xml_node cur = p;\r
+ \r
+ for (;;)\r
+ {\r
+ if (cur.first_child())\r
+ cur = cur.first_child();\r
+ else if (cur.next_sibling())\r
+ cur = cur.next_sibling();\r
+ else\r
+ {\r
+ while (cur && !cur.next_sibling()) cur = cur.parent();\r
+ cur = cur.next_sibling();\r
+ \r
+ if (!cur) break;\r
+ }\r
+\r
+ step_push(ns, cur, alloc);\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ case axis_parent:\r
+ {\r
+ step_push(ns, p, alloc);\r
+\r
+ break;\r
+ }\r
+\r
+ case axis_preceding:\r
+ {\r
+ // preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding\r
+ step_fill(ns, p, alloc, v);\r
+ break;\r
+ }\r
+ \r
+ default:\r
+ assert(!"Unimplemented axis");\r
+ }\r
+ }\r
+ \r
+ template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, T v)\r
+ {\r
+ const axis_t axis = T::axis;\r
+ bool attributes = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_descendant_or_self || axis == axis_following || axis == axis_parent || axis == axis_preceding || axis == axis_self);\r
+\r
+ xpath_node_set_raw ns;\r
+ ns.set_type((axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling) ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted);\r
+\r
+ if (_left)\r
+ {\r
+ xpath_node_set_raw s = _left->eval_node_set(c, stack);\r
+\r
+ // self axis preserves the original order\r
+ if (axis == axis_self) ns.set_type(s.type());\r
+\r
+ for (const xpath_node* it = s.begin(); it != s.end(); ++it)\r
+ {\r
+ size_t size = ns.size();\r
+\r
+ // in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes\r
+ if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted);\r
+ \r
+ if (it->node())\r
+ step_fill(ns, it->node(), stack.result, v);\r
+ else if (attributes)\r
+ step_fill(ns, it->attribute(), it->parent(), stack.result, v);\r
+ \r
+ apply_predicates(ns, size, stack);\r
+ }\r
+ }\r
+ else\r
+ {\r
+ if (c.n.node())\r
+ step_fill(ns, c.n.node(), stack.result, v);\r
+ else if (attributes)\r
+ step_fill(ns, c.n.attribute(), c.n.parent(), stack.result, v);\r
+ \r
+ apply_predicates(ns, 0, stack);\r
+ }\r
+\r
+ // child, attribute and self axes always generate unique set of nodes\r
+ // for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice\r
+ if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted)\r
+ ns.remove_duplicates();\r
+\r
+ return ns;\r
+ }\r
+ \r
+ public:\r
+ xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value):\r
+ _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)\r
+ {\r
+ assert(type == ast_string_constant);\r
+ _data.string = value;\r
+ }\r
+\r
+ xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value):\r
+ _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)\r
+ {\r
+ assert(type == ast_number_constant);\r
+ _data.number = value;\r
+ }\r
+ \r
+ xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value):\r
+ _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)\r
+ {\r
+ assert(type == ast_variable);\r
+ _data.variable = value;\r
+ }\r
+ \r
+ xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0):\r
+ _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0)\r
+ {\r
+ }\r
+\r
+ xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents):\r
+ _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(static_cast<char>(axis)), _test(static_cast<char>(test)), _left(left), _right(0), _next(0)\r
+ {\r
+ _data.nodetest = contents;\r
+ }\r
+\r
+ void set_next(xpath_ast_node* value)\r
+ {\r
+ _next = value;\r
+ }\r
+\r
+ void set_right(xpath_ast_node* value)\r
+ {\r
+ _right = value;\r
+ }\r
+\r
+ bool eval_boolean(const xpath_context& c, const xpath_stack& stack)\r
+ {\r
+ switch (_type)\r
+ {\r
+ case ast_op_or:\r
+ return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack);\r
+ \r
+ case ast_op_and:\r
+ return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack);\r
+ \r
+ case ast_op_equal:\r
+ return compare_eq(_left, _right, c, stack, equal_to());\r
+\r
+ case ast_op_not_equal:\r
+ return compare_eq(_left, _right, c, stack, not_equal_to());\r
+ \r
+ case ast_op_less:\r
+ return compare_rel(_left, _right, c, stack, less());\r
+ \r
+ case ast_op_greater:\r
+ return compare_rel(_right, _left, c, stack, less());\r
+\r
+ case ast_op_less_or_equal:\r
+ return compare_rel(_left, _right, c, stack, less_equal());\r
+ \r
+ case ast_op_greater_or_equal:\r
+ return compare_rel(_right, _left, c, stack, less_equal());\r
+\r
+ case ast_func_starts_with:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_string lr = _left->eval_string(c, stack);\r
+ xpath_string rr = _right->eval_string(c, stack);\r
+\r
+ return starts_with(lr.c_str(), rr.c_str());\r
+ }\r
+\r
+ case ast_func_contains:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_string lr = _left->eval_string(c, stack);\r
+ xpath_string rr = _right->eval_string(c, stack);\r
+\r
+ return find_substring(lr.c_str(), rr.c_str()) != 0;\r
+ }\r
+\r
+ case ast_func_boolean:\r
+ return _left->eval_boolean(c, stack);\r
+ \r
+ case ast_func_not:\r
+ return !_left->eval_boolean(c, stack);\r
+ \r
+ case ast_func_true:\r
+ return true;\r
+ \r
+ case ast_func_false:\r
+ return false;\r
+\r
+ case ast_func_lang:\r
+ {\r
+ if (c.n.attribute()) return false;\r
+ \r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_string lang = _left->eval_string(c, stack);\r
+ \r
+ for (xml_node n = c.n.node(); n; n = n.parent())\r
+ {\r
+ xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang"));\r
+ \r
+ if (a)\r
+ {\r
+ const char_t* value = a.value();\r
+ \r
+ // strnicmp / strncasecmp is not portable\r
+ for (const char_t* lit = lang.c_str(); *lit; ++lit)\r
+ {\r
+ if (tolower_ascii(*lit) != tolower_ascii(*value)) return false;\r
+ ++value;\r
+ }\r
+ \r
+ return *value == 0 || *value == '-';\r
+ }\r
+ }\r
+ \r
+ return false;\r
+ }\r
+\r
+ case ast_variable:\r
+ {\r
+ assert(_rettype == _data.variable->type());\r
+\r
+ if (_rettype == xpath_type_boolean)\r
+ return _data.variable->get_boolean();\r
+\r
+ // fallthrough to type conversion\r
+ }\r
+\r
+ default:\r
+ {\r
+ switch (_rettype)\r
+ {\r
+ case xpath_type_number:\r
+ return convert_number_to_boolean(eval_number(c, stack));\r
+ \r
+ case xpath_type_string:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return !eval_string(c, stack).empty();\r
+ }\r
+ \r
+ case xpath_type_node_set: \r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return !eval_node_set(c, stack).empty();\r
+ }\r
+\r
+ default:\r
+ assert(!"Wrong expression for return type boolean");\r
+ return false;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ double eval_number(const xpath_context& c, const xpath_stack& stack)\r
+ {\r
+ switch (_type)\r
+ {\r
+ case ast_op_add:\r
+ return _left->eval_number(c, stack) + _right->eval_number(c, stack);\r
+ \r
+ case ast_op_subtract:\r
+ return _left->eval_number(c, stack) - _right->eval_number(c, stack);\r
+\r
+ case ast_op_multiply:\r
+ return _left->eval_number(c, stack) * _right->eval_number(c, stack);\r
+\r
+ case ast_op_divide:\r
+ return _left->eval_number(c, stack) / _right->eval_number(c, stack);\r
+\r
+ case ast_op_mod:\r
+ return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack));\r
+\r
+ case ast_op_negate:\r
+ return -_left->eval_number(c, stack);\r
+\r
+ case ast_number_constant:\r
+ return _data.number;\r
+\r
+ case ast_func_last:\r
+ return static_cast<double>(c.size);\r
+ \r
+ case ast_func_position:\r
+ return static_cast<double>(c.position);\r
+\r
+ case ast_func_count:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return static_cast<double>(_left->eval_node_set(c, stack).size());\r
+ }\r
+ \r
+ case ast_func_string_length_0:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return static_cast<double>(string_value(c.n, stack.result).length());\r
+ }\r
+ \r
+ case ast_func_string_length_1:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return static_cast<double>(_left->eval_string(c, stack).length());\r
+ }\r
+ \r
+ case ast_func_number_0:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return convert_string_to_number(string_value(c.n, stack.result).c_str());\r
+ }\r
+ \r
+ case ast_func_number_1:\r
+ return _left->eval_number(c, stack);\r
+\r
+ case ast_func_sum:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ double r = 0;\r
+ \r
+ xpath_node_set_raw ns = _left->eval_node_set(c, stack);\r
+ \r
+ for (const xpath_node* it = ns.begin(); it != ns.end(); ++it)\r
+ {\r
+ xpath_allocator_capture cri(stack.result);\r
+\r
+ r += convert_string_to_number(string_value(*it, stack.result).c_str());\r
+ }\r
+ \r
+ return r;\r
+ }\r
+\r
+ case ast_func_floor:\r
+ {\r
+ double r = _left->eval_number(c, stack);\r
+ \r
+ return r == r ? floor(r) : r;\r
+ }\r
+\r
+ case ast_func_ceiling:\r
+ {\r
+ double r = _left->eval_number(c, stack);\r
+ \r
+ return r == r ? ceil(r) : r;\r
+ }\r
+\r
+ case ast_func_round:\r
+ return round_nearest_nzero(_left->eval_number(c, stack));\r
+ \r
+ case ast_variable:\r
+ {\r
+ assert(_rettype == _data.variable->type());\r
+\r
+ if (_rettype == xpath_type_number)\r
+ return _data.variable->get_number();\r
+\r
+ // fallthrough to type conversion\r
+ }\r
+\r
+ default:\r
+ {\r
+ switch (_rettype)\r
+ {\r
+ case xpath_type_boolean:\r
+ return eval_boolean(c, stack) ? 1 : 0;\r
+ \r
+ case xpath_type_string:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return convert_string_to_number(eval_string(c, stack).c_str());\r
+ }\r
+ \r
+ case xpath_type_node_set:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ return convert_string_to_number(eval_string(c, stack).c_str());\r
+ }\r
+ \r
+ default:\r
+ assert(!"Wrong expression for return type number");\r
+ return 0;\r
+ }\r
+ \r
+ }\r
+ }\r
+ }\r
+ \r
+ xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack)\r
+ {\r
+ assert(_type == ast_func_concat);\r
+\r
+ xpath_allocator_capture ct(stack.temp);\r
+\r
+ // count the string number\r
+ size_t count = 1;\r
+ for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++;\r
+\r
+ // gather all strings\r
+ xpath_string static_buffer[4];\r
+ xpath_string* buffer = static_buffer;\r
+\r
+ // allocate on-heap for large concats\r
+ if (count > sizeof(static_buffer) / sizeof(static_buffer[0]))\r
+ {\r
+ buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string)));\r
+ assert(buffer);\r
+ }\r
+\r
+ // evaluate all strings to temporary stack\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ buffer[0] = _left->eval_string(c, swapped_stack);\r
+\r
+ size_t pos = 1;\r
+ for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack);\r
+ assert(pos == count);\r
+\r
+ // get total length\r
+ size_t length = 0;\r
+ for (size_t i = 0; i < count; ++i) length += buffer[i].length();\r
+\r
+ // create final string\r
+ char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t)));\r
+ assert(result);\r
+\r
+ char_t* ri = result;\r
+\r
+ for (size_t j = 0; j < count; ++j)\r
+ for (const char_t* bi = buffer[j].c_str(); *bi; ++bi)\r
+ *ri++ = *bi;\r
+\r
+ *ri = 0;\r
+\r
+ return xpath_string(result, true);\r
+ }\r
+\r
+ xpath_string eval_string(const xpath_context& c, const xpath_stack& stack)\r
+ {\r
+ switch (_type)\r
+ {\r
+ case ast_string_constant:\r
+ return xpath_string_const(_data.string);\r
+ \r
+ case ast_func_local_name_0:\r
+ {\r
+ xpath_node na = c.n;\r
+ \r
+ return xpath_string_const(local_name(na));\r
+ }\r
+\r
+ case ast_func_local_name_1:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ns = _left->eval_node_set(c, stack);\r
+ xpath_node na = ns.first();\r
+ \r
+ return xpath_string_const(local_name(na));\r
+ }\r
+\r
+ case ast_func_name_0:\r
+ {\r
+ xpath_node na = c.n;\r
+ \r
+ return xpath_string_const(qualified_name(na));\r
+ }\r
+\r
+ case ast_func_name_1:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ns = _left->eval_node_set(c, stack);\r
+ xpath_node na = ns.first();\r
+ \r
+ return xpath_string_const(qualified_name(na));\r
+ }\r
+\r
+ case ast_func_namespace_uri_0:\r
+ {\r
+ xpath_node na = c.n;\r
+ \r
+ return xpath_string_const(namespace_uri(na));\r
+ }\r
+\r
+ case ast_func_namespace_uri_1:\r
+ {\r
+ xpath_allocator_capture cr(stack.result);\r
+\r
+ xpath_node_set_raw ns = _left->eval_node_set(c, stack);\r
+ xpath_node na = ns.first();\r
+ \r
+ return xpath_string_const(namespace_uri(na));\r
+ }\r
+\r
+ case ast_func_string_0:\r
+ return string_value(c.n, stack.result);\r
+\r
+ case ast_func_string_1:\r
+ return _left->eval_string(c, stack);\r
+\r
+ case ast_func_concat:\r
+ return eval_string_concat(c, stack);\r
+\r
+ case ast_func_substring_before:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_string s = _left->eval_string(c, swapped_stack);\r
+ xpath_string p = _right->eval_string(c, swapped_stack);\r
+\r
+ const char_t* pos = find_substring(s.c_str(), p.c_str());\r
+ \r
+ return pos ? xpath_string(s.c_str(), pos, stack.result) : xpath_string();\r
+ }\r
+ \r
+ case ast_func_substring_after:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_string s = _left->eval_string(c, swapped_stack);\r
+ xpath_string p = _right->eval_string(c, swapped_stack);\r
+ \r
+ const char_t* pos = find_substring(s.c_str(), p.c_str());\r
+ if (!pos) return xpath_string();\r
+\r
+ const char_t* result = pos + p.length();\r
+\r
+ return s.uses_heap() ? xpath_string(result, stack.result) : xpath_string_const(result);\r
+ }\r
+\r
+ case ast_func_substring_2:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_string s = _left->eval_string(c, swapped_stack);\r
+ size_t s_length = s.length();\r
+\r
+ double first = round_nearest(_right->eval_number(c, stack));\r
+ \r
+ if (is_nan(first)) return xpath_string(); // NaN\r
+ else if (first >= s_length + 1) return xpath_string();\r
+ \r
+ size_t pos = first < 1 ? 1 : static_cast<size_t>(first);\r
+ assert(1 <= pos && pos <= s_length + 1);\r
+\r
+ const char_t* rbegin = s.c_str() + (pos - 1);\r
+ \r
+ return s.uses_heap() ? xpath_string(rbegin, stack.result) : xpath_string_const(rbegin);\r
+ }\r
+ \r
+ case ast_func_substring_3:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_string s = _left->eval_string(c, swapped_stack);\r
+ size_t s_length = s.length();\r
+\r
+ double first = round_nearest(_right->eval_number(c, stack));\r
+ double last = first + round_nearest(_right->_next->eval_number(c, stack));\r
+ \r
+ if (is_nan(first) || is_nan(last)) return xpath_string();\r
+ else if (first >= s_length + 1) return xpath_string();\r
+ else if (first >= last) return xpath_string();\r
+ else if (last < 1) return xpath_string();\r
+ \r
+ size_t pos = first < 1 ? 1 : static_cast<size_t>(first);\r
+ size_t end = last >= s_length + 1 ? s_length + 1 : static_cast<size_t>(last);\r
+\r
+ assert(1 <= pos && pos <= end && end <= s_length + 1);\r
+ const char_t* rbegin = s.c_str() + (pos - 1);\r
+ const char_t* rend = s.c_str() + (end - 1);\r
+\r
+ return (end == s_length + 1 && !s.uses_heap()) ? xpath_string_const(rbegin) : xpath_string(rbegin, rend, stack.result);\r
+ }\r
+\r
+ case ast_func_normalize_space_0:\r
+ {\r
+ xpath_string s = string_value(c.n, stack.result);\r
+\r
+ normalize_space(s.data(stack.result));\r
+\r
+ return s;\r
+ }\r
+\r
+ case ast_func_normalize_space_1:\r
+ {\r
+ xpath_string s = _left->eval_string(c, stack);\r
+\r
+ normalize_space(s.data(stack.result));\r
+ \r
+ return s;\r
+ }\r
+\r
+ case ast_func_translate:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_string s = _left->eval_string(c, stack);\r
+ xpath_string from = _right->eval_string(c, swapped_stack);\r
+ xpath_string to = _right->_next->eval_string(c, swapped_stack);\r
+\r
+ translate(s.data(stack.result), from.c_str(), to.c_str());\r
+\r
+ return s;\r
+ }\r
+\r
+ case ast_variable:\r
+ {\r
+ assert(_rettype == _data.variable->type());\r
+\r
+ if (_rettype == xpath_type_string)\r
+ return xpath_string_const(_data.variable->get_string());\r
+\r
+ // fallthrough to type conversion\r
+ }\r
+\r
+ default:\r
+ {\r
+ switch (_rettype)\r
+ {\r
+ case xpath_type_boolean:\r
+ return xpath_string_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));\r
+ \r
+ case xpath_type_number:\r
+ return convert_number_to_string(eval_number(c, stack), stack.result);\r
+ \r
+ case xpath_type_node_set:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_node_set_raw ns = eval_node_set(c, swapped_stack);\r
+ return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result);\r
+ }\r
+ \r
+ default:\r
+ assert(!"Wrong expression for return type string");\r
+ return xpath_string();\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack)\r
+ {\r
+ switch (_type)\r
+ {\r
+ case ast_op_union:\r
+ {\r
+ xpath_allocator_capture cr(stack.temp);\r
+\r
+ xpath_stack swapped_stack = {stack.temp, stack.result};\r
+\r
+ xpath_node_set_raw ls = _left->eval_node_set(c, swapped_stack);\r
+ xpath_node_set_raw rs = _right->eval_node_set(c, stack);\r
+ \r
+ // we can optimize merging two sorted sets, but this is a very rare operation, so don't bother\r
+ rs.set_type(xpath_node_set::type_unsorted);\r
+\r
+ rs.append(ls.begin(), ls.end(), stack.result);\r
+ rs.remove_duplicates();\r
+ \r
+ return rs;\r
+ }\r
+\r
+ case ast_filter:\r
+ case ast_filter_posinv:\r
+ {\r
+ xpath_node_set_raw set = _left->eval_node_set(c, stack);\r
+\r
+ // either expression is a number or it contains position() call; sort by document order\r
+ if (_type == ast_filter) set.sort_do();\r
+\r
+ apply_predicate(set, 0, _right, stack);\r
+ \r
+ return set;\r
+ }\r
+ \r
+ case ast_func_id:\r
+ return xpath_node_set_raw();\r
+ \r
+ case ast_step:\r
+ {\r
+ switch (_axis)\r
+ {\r
+ case axis_ancestor:\r
+ return step_do(c, stack, axis_to_type<axis_ancestor>());\r
+ \r
+ case axis_ancestor_or_self:\r
+ return step_do(c, stack, axis_to_type<axis_ancestor_or_self>());\r
+\r
+ case axis_attribute:\r
+ return step_do(c, stack, axis_to_type<axis_attribute>());\r
+\r
+ case axis_child:\r
+ return step_do(c, stack, axis_to_type<axis_child>());\r
+ \r
+ case axis_descendant:\r
+ return step_do(c, stack, axis_to_type<axis_descendant>());\r
+\r
+ case axis_descendant_or_self:\r
+ return step_do(c, stack, axis_to_type<axis_descendant_or_self>());\r
+\r
+ case axis_following:\r
+ return step_do(c, stack, axis_to_type<axis_following>());\r
+ \r
+ case axis_following_sibling:\r
+ return step_do(c, stack, axis_to_type<axis_following_sibling>());\r
+ \r
+ case axis_namespace:\r
+ // namespaced axis is not supported\r
+ return xpath_node_set_raw();\r
+ \r
+ case axis_parent:\r
+ return step_do(c, stack, axis_to_type<axis_parent>());\r
+ \r
+ case axis_preceding:\r
+ return step_do(c, stack, axis_to_type<axis_preceding>());\r
+\r
+ case axis_preceding_sibling:\r
+ return step_do(c, stack, axis_to_type<axis_preceding_sibling>());\r
+ \r
+ case axis_self:\r
+ return step_do(c, stack, axis_to_type<axis_self>());\r
+\r
+ default:\r
+ assert(!"Unknown axis");\r
+ return xpath_node_set_raw();\r
+ }\r
+ }\r
+\r
+ case ast_step_root:\r
+ {\r
+ assert(!_right); // root step can't have any predicates\r
+\r
+ xpath_node_set_raw ns;\r
+\r
+ ns.set_type(xpath_node_set::type_sorted);\r
+\r
+ if (c.n.node()) ns.push_back(c.n.node().root(), stack.result);\r
+ else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result);\r
+\r
+ return ns;\r
+ }\r
+\r
+ case ast_variable:\r
+ {\r
+ assert(_rettype == _data.variable->type());\r
+\r
+ if (_rettype == xpath_type_node_set)\r
+ {\r
+ const xpath_node_set& s = _data.variable->get_node_set();\r
+\r
+ xpath_node_set_raw ns;\r
+\r
+ ns.set_type(s.type());\r
+ ns.append(s.begin(), s.end(), stack.result);\r
+\r
+ return ns;\r
+ }\r
+\r
+ // fallthrough to type conversion\r
+ }\r
+\r
+ default:\r
+ assert(!"Wrong expression for return type node set");\r
+ return xpath_node_set_raw();\r
+ }\r
+ }\r
+ \r
+ bool is_posinv()\r
+ {\r
+ switch (_type)\r
+ {\r
+ case ast_func_position:\r
+ return false;\r
+\r
+ case ast_string_constant:\r
+ case ast_number_constant:\r
+ case ast_variable:\r
+ return true;\r
+\r
+ case ast_step:\r
+ case ast_step_root:\r
+ return true;\r
+\r
+ case ast_predicate:\r
+ case ast_filter:\r
+ case ast_filter_posinv:\r
+ return true;\r
+\r
+ default:\r
+ if (_left && !_left->is_posinv()) return false;\r
+ \r
+ for (xpath_ast_node* n = _right; n; n = n->_next)\r
+ if (!n->is_posinv()) return false;\r
+ \r
+ return true;\r
+ }\r
+ }\r
+\r
+ xpath_value_type rettype() const\r
+ {\r
+ return static_cast<xpath_value_type>(_rettype);\r
+ }\r
+ };\r
+\r
+ struct xpath_parser\r
+ {\r
+ xpath_allocator* _alloc;\r
+ xpath_lexer _lexer;\r
+\r
+ const char_t* _query;\r
+ xpath_variable_set* _variables;\r
+\r
+ xpath_parse_result* _result;\r
+\r
+ char_t _scratch[32];\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ jmp_buf _error_handler;\r
+ #endif\r
+\r
+ void throw_error(const char* message)\r
+ {\r
+ _result->error = message;\r
+ _result->offset = _lexer.current_pos() - _query;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ longjmp(_error_handler, 1);\r
+ #else\r
+ throw xpath_exception(*_result);\r
+ #endif\r
+ }\r
+\r
+ void throw_error_oom()\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ throw_error("Out of memory");\r
+ #else\r
+ throw std::bad_alloc();\r
+ #endif\r
+ }\r
+\r
+ void* alloc_node()\r
+ {\r
+ void* result = _alloc->allocate_nothrow(sizeof(xpath_ast_node));\r
+\r
+ if (!result) throw_error_oom();\r
+\r
+ return result;\r
+ }\r
+\r
+ const char_t* alloc_string(const xpath_lexer_string& value)\r
+ {\r
+ if (value.begin)\r
+ {\r
+ size_t length = static_cast<size_t>(value.end - value.begin);\r
+\r
+ char_t* c = static_cast<char_t*>(_alloc->allocate_nothrow((length + 1) * sizeof(char_t)));\r
+ if (!c) throw_error_oom();\r
+ assert(c); // workaround for clang static analysis\r
+\r
+ memcpy(c, value.begin, length * sizeof(char_t));\r
+ c[length] = 0;\r
+\r
+ return c;\r
+ }\r
+ else return 0;\r
+ }\r
+\r
+ xpath_ast_node* parse_function_helper(ast_type_t type0, ast_type_t type1, size_t argc, xpath_ast_node* args[2])\r
+ {\r
+ assert(argc <= 1);\r
+\r
+ if (argc == 1 && args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");\r
+\r
+ return new (alloc_node()) xpath_ast_node(argc == 0 ? type0 : type1, xpath_type_string, args[0]);\r
+ }\r
+\r
+ xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2])\r
+ {\r
+ switch (name.begin[0])\r
+ {\r
+ case 'b':\r
+ if (name == PUGIXML_TEXT("boolean") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_boolean, xpath_type_boolean, args[0]);\r
+ \r
+ break;\r
+ \r
+ case 'c':\r
+ if (name == PUGIXML_TEXT("count") && argc == 1)\r
+ {\r
+ if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");\r
+ return new (alloc_node()) xpath_ast_node(ast_func_count, xpath_type_number, args[0]);\r
+ }\r
+ else if (name == PUGIXML_TEXT("contains") && argc == 2)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_contains, xpath_type_boolean, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("concat") && argc >= 2)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_concat, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("ceiling") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_ceiling, xpath_type_number, args[0]);\r
+ \r
+ break;\r
+ \r
+ case 'f':\r
+ if (name == PUGIXML_TEXT("false") && argc == 0)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_false, xpath_type_boolean);\r
+ else if (name == PUGIXML_TEXT("floor") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_floor, xpath_type_number, args[0]);\r
+ \r
+ break;\r
+ \r
+ case 'i':\r
+ if (name == PUGIXML_TEXT("id") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_id, xpath_type_node_set, args[0]);\r
+ \r
+ break;\r
+ \r
+ case 'l':\r
+ if (name == PUGIXML_TEXT("last") && argc == 0)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_last, xpath_type_number);\r
+ else if (name == PUGIXML_TEXT("lang") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_lang, xpath_type_boolean, args[0]);\r
+ else if (name == PUGIXML_TEXT("local-name") && argc <= 1)\r
+ return parse_function_helper(ast_func_local_name_0, ast_func_local_name_1, argc, args);\r
+ \r
+ break;\r
+ \r
+ case 'n':\r
+ if (name == PUGIXML_TEXT("name") && argc <= 1)\r
+ return parse_function_helper(ast_func_name_0, ast_func_name_1, argc, args);\r
+ else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1)\r
+ return parse_function_helper(ast_func_namespace_uri_0, ast_func_namespace_uri_1, argc, args);\r
+ else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1)\r
+ return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("not") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_not, xpath_type_boolean, args[0]);\r
+ else if (name == PUGIXML_TEXT("number") && argc <= 1)\r
+ return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]);\r
+ \r
+ break;\r
+ \r
+ case 'p':\r
+ if (name == PUGIXML_TEXT("position") && argc == 0)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_position, xpath_type_number);\r
+ \r
+ break;\r
+ \r
+ case 'r':\r
+ if (name == PUGIXML_TEXT("round") && argc == 1)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_round, xpath_type_number, args[0]);\r
+\r
+ break;\r
+ \r
+ case 's':\r
+ if (name == PUGIXML_TEXT("string") && argc <= 1)\r
+ return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]);\r
+ else if (name == PUGIXML_TEXT("string-length") && argc <= 1)\r
+ return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_number, args[0]);\r
+ else if (name == PUGIXML_TEXT("starts-with") && argc == 2)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("substring-before") && argc == 2)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_substring_before, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("substring-after") && argc == 2)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_substring_after, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3))\r
+ return new (alloc_node()) xpath_ast_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("sum") && argc == 1)\r
+ {\r
+ if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");\r
+ return new (alloc_node()) xpath_ast_node(ast_func_sum, xpath_type_number, args[0]);\r
+ }\r
+\r
+ break;\r
+ \r
+ case 't':\r
+ if (name == PUGIXML_TEXT("translate") && argc == 3)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_translate, xpath_type_string, args[0], args[1]);\r
+ else if (name == PUGIXML_TEXT("true") && argc == 0)\r
+ return new (alloc_node()) xpath_ast_node(ast_func_true, xpath_type_boolean);\r
+ \r
+ break;\r
+\r
+ default:\r
+ break;\r
+ }\r
+\r
+ throw_error("Unrecognized function or wrong parameter count");\r
+\r
+ return 0;\r
+ }\r
+\r
+ axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified)\r
+ {\r
+ specified = true;\r
+\r
+ switch (name.begin[0])\r
+ {\r
+ case 'a':\r
+ if (name == PUGIXML_TEXT("ancestor"))\r
+ return axis_ancestor;\r
+ else if (name == PUGIXML_TEXT("ancestor-or-self"))\r
+ return axis_ancestor_or_self;\r
+ else if (name == PUGIXML_TEXT("attribute"))\r
+ return axis_attribute;\r
+ \r
+ break;\r
+ \r
+ case 'c':\r
+ if (name == PUGIXML_TEXT("child"))\r
+ return axis_child;\r
+ \r
+ break;\r
+ \r
+ case 'd':\r
+ if (name == PUGIXML_TEXT("descendant"))\r
+ return axis_descendant;\r
+ else if (name == PUGIXML_TEXT("descendant-or-self"))\r
+ return axis_descendant_or_self;\r
+ \r
+ break;\r
+ \r
+ case 'f':\r
+ if (name == PUGIXML_TEXT("following"))\r
+ return axis_following;\r
+ else if (name == PUGIXML_TEXT("following-sibling"))\r
+ return axis_following_sibling;\r
+ \r
+ break;\r
+ \r
+ case 'n':\r
+ if (name == PUGIXML_TEXT("namespace"))\r
+ return axis_namespace;\r
+ \r
+ break;\r
+ \r
+ case 'p':\r
+ if (name == PUGIXML_TEXT("parent"))\r
+ return axis_parent;\r
+ else if (name == PUGIXML_TEXT("preceding"))\r
+ return axis_preceding;\r
+ else if (name == PUGIXML_TEXT("preceding-sibling"))\r
+ return axis_preceding_sibling;\r
+ \r
+ break;\r
+ \r
+ case 's':\r
+ if (name == PUGIXML_TEXT("self"))\r
+ return axis_self;\r
+ \r
+ break;\r
+\r
+ default:\r
+ break;\r
+ }\r
+\r
+ specified = false;\r
+ return axis_child;\r
+ }\r
+\r
+ nodetest_t parse_node_test_type(const xpath_lexer_string& name)\r
+ {\r
+ switch (name.begin[0])\r
+ {\r
+ case 'c':\r
+ if (name == PUGIXML_TEXT("comment"))\r
+ return nodetest_type_comment;\r
+\r
+ break;\r
+\r
+ case 'n':\r
+ if (name == PUGIXML_TEXT("node"))\r
+ return nodetest_type_node;\r
+\r
+ break;\r
+\r
+ case 'p':\r
+ if (name == PUGIXML_TEXT("processing-instruction"))\r
+ return nodetest_type_pi;\r
+\r
+ break;\r
+\r
+ case 't':\r
+ if (name == PUGIXML_TEXT("text"))\r
+ return nodetest_type_text;\r
+\r
+ break;\r
+ \r
+ default:\r
+ break;\r
+ }\r
+\r
+ return nodetest_none;\r
+ }\r
+\r
+ // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall\r
+ xpath_ast_node* parse_primary_expression()\r
+ {\r
+ switch (_lexer.current())\r
+ {\r
+ case lex_var_ref:\r
+ {\r
+ xpath_lexer_string name = _lexer.contents();\r
+\r
+ if (!_variables)\r
+ throw_error("Unknown variable: variable set is not provided");\r
+\r
+ xpath_variable* var = get_variable_scratch(_scratch, _variables, name.begin, name.end);\r
+\r
+ if (!var)\r
+ throw_error("Unknown variable: variable set does not contain the given name");\r
+\r
+ _lexer.next();\r
+\r
+ return new (alloc_node()) xpath_ast_node(ast_variable, var->type(), var);\r
+ }\r
+\r
+ case lex_open_brace:\r
+ {\r
+ _lexer.next();\r
+\r
+ xpath_ast_node* n = parse_expression();\r
+\r
+ if (_lexer.current() != lex_close_brace)\r
+ throw_error("Unmatched braces");\r
+\r
+ _lexer.next();\r
+\r
+ return n;\r
+ }\r
+\r
+ case lex_quoted_string:\r
+ {\r
+ const char_t* value = alloc_string(_lexer.contents());\r
+\r
+ xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_string_constant, xpath_type_string, value);\r
+ _lexer.next();\r
+\r
+ return n;\r
+ }\r
+\r
+ case lex_number:\r
+ {\r
+ double value = 0;\r
+\r
+ if (!convert_string_to_number_scratch(_scratch, _lexer.contents().begin, _lexer.contents().end, &value))\r
+ throw_error_oom();\r
+\r
+ xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_number_constant, xpath_type_number, value);\r
+ _lexer.next();\r
+\r
+ return n;\r
+ }\r
+\r
+ case lex_string:\r
+ {\r
+ xpath_ast_node* args[2] = {0};\r
+ size_t argc = 0;\r
+ \r
+ xpath_lexer_string function = _lexer.contents();\r
+ _lexer.next();\r
+ \r
+ xpath_ast_node* last_arg = 0;\r
+ \r
+ if (_lexer.current() != lex_open_brace)\r
+ throw_error("Unrecognized function call");\r
+ _lexer.next();\r
+\r
+ if (_lexer.current() != lex_close_brace)\r
+ args[argc++] = parse_expression();\r
+\r
+ while (_lexer.current() != lex_close_brace)\r
+ {\r
+ if (_lexer.current() != lex_comma)\r
+ throw_error("No comma between function arguments");\r
+ _lexer.next();\r
+ \r
+ xpath_ast_node* n = parse_expression();\r
+ \r
+ if (argc < 2) args[argc] = n;\r
+ else last_arg->set_next(n);\r
+\r
+ argc++;\r
+ last_arg = n;\r
+ }\r
+ \r
+ _lexer.next();\r
+\r
+ return parse_function(function, argc, args);\r
+ }\r
+\r
+ default:\r
+ throw_error("Unrecognizable primary expression");\r
+\r
+ return 0;\r
+ }\r
+ }\r
+ \r
+ // FilterExpr ::= PrimaryExpr | FilterExpr Predicate\r
+ // Predicate ::= '[' PredicateExpr ']'\r
+ // PredicateExpr ::= Expr\r
+ xpath_ast_node* parse_filter_expression()\r
+ {\r
+ xpath_ast_node* n = parse_primary_expression();\r
+\r
+ while (_lexer.current() == lex_open_square_brace)\r
+ {\r
+ _lexer.next();\r
+\r
+ xpath_ast_node* expr = parse_expression();\r
+\r
+ if (n->rettype() != xpath_type_node_set) throw_error("Predicate has to be applied to node set");\r
+\r
+ bool posinv = expr->rettype() != xpath_type_number && expr->is_posinv();\r
+\r
+ n = new (alloc_node()) xpath_ast_node(posinv ? ast_filter_posinv : ast_filter, xpath_type_node_set, n, expr);\r
+\r
+ if (_lexer.current() != lex_close_square_brace)\r
+ throw_error("Unmatched square brace");\r
+ \r
+ _lexer.next();\r
+ }\r
+ \r
+ return n;\r
+ }\r
+ \r
+ // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep\r
+ // AxisSpecifier ::= AxisName '::' | '@'?\r
+ // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'\r
+ // NameTest ::= '*' | NCName ':' '*' | QName\r
+ // AbbreviatedStep ::= '.' | '..'\r
+ xpath_ast_node* parse_step(xpath_ast_node* set)\r
+ {\r
+ if (set && set->rettype() != xpath_type_node_set)\r
+ throw_error("Step has to be applied to node set");\r
+\r
+ bool axis_specified = false;\r
+ axis_t axis = axis_child; // implied child axis\r
+\r
+ if (_lexer.current() == lex_axis_attribute)\r
+ {\r
+ axis = axis_attribute;\r
+ axis_specified = true;\r
+ \r
+ _lexer.next();\r
+ }\r
+ else if (_lexer.current() == lex_dot)\r
+ {\r
+ _lexer.next();\r
+ \r
+ return new (alloc_node()) xpath_ast_node(ast_step, set, axis_self, nodetest_type_node, 0);\r
+ }\r
+ else if (_lexer.current() == lex_double_dot)\r
+ {\r
+ _lexer.next();\r
+ \r
+ return new (alloc_node()) xpath_ast_node(ast_step, set, axis_parent, nodetest_type_node, 0);\r
+ }\r
+ \r
+ nodetest_t nt_type = nodetest_none;\r
+ xpath_lexer_string nt_name;\r
+ \r
+ if (_lexer.current() == lex_string)\r
+ {\r
+ // node name test\r
+ nt_name = _lexer.contents();\r
+ _lexer.next();\r
+\r
+ // was it an axis name?\r
+ if (_lexer.current() == lex_double_colon)\r
+ {\r
+ // parse axis name\r
+ if (axis_specified) throw_error("Two axis specifiers in one step");\r
+\r
+ axis = parse_axis_name(nt_name, axis_specified);\r
+\r
+ if (!axis_specified) throw_error("Unknown axis");\r
+\r
+ // read actual node test\r
+ _lexer.next();\r
+\r
+ if (_lexer.current() == lex_multiply)\r
+ {\r
+ nt_type = nodetest_all;\r
+ nt_name = xpath_lexer_string();\r
+ _lexer.next();\r
+ }\r
+ else if (_lexer.current() == lex_string)\r
+ {\r
+ nt_name = _lexer.contents();\r
+ _lexer.next();\r
+ }\r
+ else throw_error("Unrecognized node test");\r
+ }\r
+ \r
+ if (nt_type == nodetest_none)\r
+ {\r
+ // node type test or processing-instruction\r
+ if (_lexer.current() == lex_open_brace)\r
+ {\r
+ _lexer.next();\r
+ \r
+ if (_lexer.current() == lex_close_brace)\r
+ {\r
+ _lexer.next();\r
+\r
+ nt_type = parse_node_test_type(nt_name);\r
+\r
+ if (nt_type == nodetest_none) throw_error("Unrecognized node type");\r
+ \r
+ nt_name = xpath_lexer_string();\r
+ }\r
+ else if (nt_name == PUGIXML_TEXT("processing-instruction"))\r
+ {\r
+ if (_lexer.current() != lex_quoted_string)\r
+ throw_error("Only literals are allowed as arguments to processing-instruction()");\r
+ \r
+ nt_type = nodetest_pi;\r
+ nt_name = _lexer.contents();\r
+ _lexer.next();\r
+ \r
+ if (_lexer.current() != lex_close_brace)\r
+ throw_error("Unmatched brace near processing-instruction()");\r
+ _lexer.next();\r
+ }\r
+ else\r
+ throw_error("Unmatched brace near node type test");\r
+\r
+ }\r
+ // QName or NCName:*\r
+ else\r
+ {\r
+ if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:*\r
+ {\r
+ nt_name.end--; // erase *\r
+ \r
+ nt_type = nodetest_all_in_namespace;\r
+ }\r
+ else nt_type = nodetest_name;\r
+ }\r
+ }\r
+ }\r
+ else if (_lexer.current() == lex_multiply)\r
+ {\r
+ nt_type = nodetest_all;\r
+ _lexer.next();\r
+ }\r
+ else throw_error("Unrecognized node test");\r
+ \r
+ xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step, set, axis, nt_type, alloc_string(nt_name));\r
+ \r
+ xpath_ast_node* last = 0;\r
+ \r
+ while (_lexer.current() == lex_open_square_brace)\r
+ {\r
+ _lexer.next();\r
+ \r
+ xpath_ast_node* expr = parse_expression();\r
+\r
+ xpath_ast_node* pred = new (alloc_node()) xpath_ast_node(ast_predicate, xpath_type_node_set, expr);\r
+ \r
+ if (_lexer.current() != lex_close_square_brace)\r
+ throw_error("Unmatched square brace");\r
+ _lexer.next();\r
+ \r
+ if (last) last->set_next(pred);\r
+ else n->set_right(pred);\r
+ \r
+ last = pred;\r
+ }\r
+ \r
+ return n;\r
+ }\r
+ \r
+ // RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step\r
+ xpath_ast_node* parse_relative_location_path(xpath_ast_node* set)\r
+ {\r
+ xpath_ast_node* n = parse_step(set);\r
+ \r
+ while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)\r
+ {\r
+ lexeme_t l = _lexer.current();\r
+ _lexer.next();\r
+\r
+ if (l == lex_double_slash)\r
+ n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);\r
+ \r
+ n = parse_step(n);\r
+ }\r
+ \r
+ return n;\r
+ }\r
+ \r
+ // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath\r
+ // AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath\r
+ xpath_ast_node* parse_location_path()\r
+ {\r
+ if (_lexer.current() == lex_slash)\r
+ {\r
+ _lexer.next();\r
+ \r
+ xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);\r
+\r
+ // relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path\r
+ lexeme_t l = _lexer.current();\r
+\r
+ if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply)\r
+ return parse_relative_location_path(n);\r
+ else\r
+ return n;\r
+ }\r
+ else if (_lexer.current() == lex_double_slash)\r
+ {\r
+ _lexer.next();\r
+ \r
+ xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);\r
+ n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);\r
+ \r
+ return parse_relative_location_path(n);\r
+ }\r
+\r
+ // else clause moved outside of if because of bogus warning 'control may reach end of non-void function being inlined' in gcc 4.0.1\r
+ return parse_relative_location_path(0);\r
+ }\r
+ \r
+ // PathExpr ::= LocationPath\r
+ // | FilterExpr\r
+ // | FilterExpr '/' RelativeLocationPath\r
+ // | FilterExpr '//' RelativeLocationPath\r
+ // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr\r
+ // UnaryExpr ::= UnionExpr | '-' UnaryExpr\r
+ xpath_ast_node* parse_path_or_unary_expression()\r
+ {\r
+ // Clarification.\r
+ // PathExpr begins with either LocationPath or FilterExpr.\r
+ // FilterExpr begins with PrimaryExpr\r
+ // PrimaryExpr begins with '$' in case of it being a variable reference,\r
+ // '(' in case of it being an expression, string literal, number constant or\r
+ // function call.\r
+\r
+ if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace || \r
+ _lexer.current() == lex_quoted_string || _lexer.current() == lex_number ||\r
+ _lexer.current() == lex_string)\r
+ {\r
+ if (_lexer.current() == lex_string)\r
+ {\r
+ // This is either a function call, or not - if not, we shall proceed with location path\r
+ const char_t* state = _lexer.state();\r
+ \r
+ while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state;\r
+ \r
+ if (*state != '(') return parse_location_path();\r
+\r
+ // This looks like a function call; however this still can be a node-test. Check it.\r
+ if (parse_node_test_type(_lexer.contents()) != nodetest_none) return parse_location_path();\r
+ }\r
+ \r
+ xpath_ast_node* n = parse_filter_expression();\r
+\r
+ if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)\r
+ {\r
+ lexeme_t l = _lexer.current();\r
+ _lexer.next();\r
+ \r
+ if (l == lex_double_slash)\r
+ {\r
+ if (n->rettype() != xpath_type_node_set) throw_error("Step has to be applied to node set");\r
+\r
+ n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);\r
+ }\r
+ \r
+ // select from location path\r
+ return parse_relative_location_path(n);\r
+ }\r
+\r
+ return n;\r
+ }\r
+ else if (_lexer.current() == lex_minus)\r
+ {\r
+ _lexer.next();\r
+\r
+ // precedence 7+ - only parses union expressions\r
+ xpath_ast_node* expr = parse_expression_rec(parse_path_or_unary_expression(), 7);\r
+\r
+ return new (alloc_node()) xpath_ast_node(ast_op_negate, xpath_type_number, expr);\r
+ }\r
+ else\r
+ return parse_location_path();\r
+ }\r
+\r
+ struct binary_op_t\r
+ {\r
+ ast_type_t asttype;\r
+ xpath_value_type rettype;\r
+ int precedence;\r
+\r
+ binary_op_t(): asttype(ast_unknown), rettype(xpath_type_none), precedence(0)\r
+ {\r
+ }\r
+\r
+ binary_op_t(ast_type_t asttype_, xpath_value_type rettype_, int precedence_): asttype(asttype_), rettype(rettype_), precedence(precedence_)\r
+ {\r
+ }\r
+\r
+ static binary_op_t parse(xpath_lexer& lexer)\r
+ {\r
+ switch (lexer.current())\r
+ {\r
+ case lex_string:\r
+ if (lexer.contents() == PUGIXML_TEXT("or"))\r
+ return binary_op_t(ast_op_or, xpath_type_boolean, 1);\r
+ else if (lexer.contents() == PUGIXML_TEXT("and"))\r
+ return binary_op_t(ast_op_and, xpath_type_boolean, 2);\r
+ else if (lexer.contents() == PUGIXML_TEXT("div"))\r
+ return binary_op_t(ast_op_divide, xpath_type_number, 6);\r
+ else if (lexer.contents() == PUGIXML_TEXT("mod"))\r
+ return binary_op_t(ast_op_mod, xpath_type_number, 6);\r
+ else\r
+ return binary_op_t();\r
+\r
+ case lex_equal:\r
+ return binary_op_t(ast_op_equal, xpath_type_boolean, 3);\r
+\r
+ case lex_not_equal:\r
+ return binary_op_t(ast_op_not_equal, xpath_type_boolean, 3);\r
+\r
+ case lex_less:\r
+ return binary_op_t(ast_op_less, xpath_type_boolean, 4);\r
+\r
+ case lex_greater:\r
+ return binary_op_t(ast_op_greater, xpath_type_boolean, 4);\r
+\r
+ case lex_less_or_equal:\r
+ return binary_op_t(ast_op_less_or_equal, xpath_type_boolean, 4);\r
+\r
+ case lex_greater_or_equal:\r
+ return binary_op_t(ast_op_greater_or_equal, xpath_type_boolean, 4);\r
+\r
+ case lex_plus:\r
+ return binary_op_t(ast_op_add, xpath_type_number, 5);\r
+\r
+ case lex_minus:\r
+ return binary_op_t(ast_op_subtract, xpath_type_number, 5);\r
+\r
+ case lex_multiply:\r
+ return binary_op_t(ast_op_multiply, xpath_type_number, 6);\r
+\r
+ case lex_union:\r
+ return binary_op_t(ast_op_union, xpath_type_node_set, 7);\r
+\r
+ default:\r
+ return binary_op_t();\r
+ }\r
+ }\r
+ };\r
+\r
+ xpath_ast_node* parse_expression_rec(xpath_ast_node* lhs, int limit)\r
+ {\r
+ binary_op_t op = binary_op_t::parse(_lexer);\r
+\r
+ while (op.asttype != ast_unknown && op.precedence >= limit)\r
+ {\r
+ _lexer.next();\r
+\r
+ xpath_ast_node* rhs = parse_path_or_unary_expression();\r
+\r
+ binary_op_t nextop = binary_op_t::parse(_lexer);\r
+\r
+ while (nextop.asttype != ast_unknown && nextop.precedence > op.precedence)\r
+ {\r
+ rhs = parse_expression_rec(rhs, nextop.precedence);\r
+\r
+ nextop = binary_op_t::parse(_lexer);\r
+ }\r
+\r
+ if (op.asttype == ast_op_union && (lhs->rettype() != xpath_type_node_set || rhs->rettype() != xpath_type_node_set))\r
+ throw_error("Union operator has to be applied to node sets");\r
+\r
+ lhs = new (alloc_node()) xpath_ast_node(op.asttype, op.rettype, lhs, rhs);\r
+\r
+ op = binary_op_t::parse(_lexer);\r
+ }\r
+\r
+ return lhs;\r
+ }\r
+\r
+ // Expr ::= OrExpr\r
+ // OrExpr ::= AndExpr | OrExpr 'or' AndExpr\r
+ // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr\r
+ // EqualityExpr ::= RelationalExpr\r
+ // | EqualityExpr '=' RelationalExpr\r
+ // | EqualityExpr '!=' RelationalExpr\r
+ // RelationalExpr ::= AdditiveExpr\r
+ // | RelationalExpr '<' AdditiveExpr\r
+ // | RelationalExpr '>' AdditiveExpr\r
+ // | RelationalExpr '<=' AdditiveExpr\r
+ // | RelationalExpr '>=' AdditiveExpr\r
+ // AdditiveExpr ::= MultiplicativeExpr\r
+ // | AdditiveExpr '+' MultiplicativeExpr\r
+ // | AdditiveExpr '-' MultiplicativeExpr\r
+ // MultiplicativeExpr ::= UnaryExpr\r
+ // | MultiplicativeExpr '*' UnaryExpr\r
+ // | MultiplicativeExpr 'div' UnaryExpr\r
+ // | MultiplicativeExpr 'mod' UnaryExpr\r
+ xpath_ast_node* parse_expression()\r
+ {\r
+ return parse_expression_rec(parse_path_or_unary_expression(), 0);\r
+ }\r
+\r
+ xpath_parser(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result): _alloc(alloc), _lexer(query), _query(query), _variables(variables), _result(result)\r
+ {\r
+ }\r
+\r
+ xpath_ast_node* parse()\r
+ {\r
+ xpath_ast_node* result = parse_expression();\r
+ \r
+ if (_lexer.current() != lex_eof)\r
+ {\r
+ // there are still unparsed tokens left, error\r
+ throw_error("Incorrect query");\r
+ }\r
+ \r
+ return result;\r
+ }\r
+\r
+ static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result)\r
+ {\r
+ xpath_parser parser(query, variables, alloc, result);\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ int error = setjmp(parser._error_handler);\r
+\r
+ return (error == 0) ? parser.parse() : 0;\r
+ #else\r
+ return parser.parse();\r
+ #endif\r
+ }\r
+ };\r
+\r
+ struct xpath_query_impl\r
+ {\r
+ static xpath_query_impl* create()\r
+ {\r
+ void* memory = xml_memory::allocate(sizeof(xpath_query_impl));\r
+\r
+ return new (memory) xpath_query_impl();\r
+ }\r
+\r
+ static void destroy(void* ptr)\r
+ {\r
+ if (!ptr) return;\r
+ \r
+ // free all allocated pages\r
+ static_cast<xpath_query_impl*>(ptr)->alloc.release();\r
+\r
+ // free allocator memory (with the first page)\r
+ xml_memory::deallocate(ptr);\r
+ }\r
+\r
+ xpath_query_impl(): root(0), alloc(&block)\r
+ {\r
+ block.next = 0;\r
+ }\r
+\r
+ xpath_ast_node* root;\r
+ xpath_allocator alloc;\r
+ xpath_memory_block block;\r
+ };\r
+\r
+ PUGI__FN xpath_string evaluate_string_impl(xpath_query_impl* impl, const xpath_node& n, xpath_stack_data& sd)\r
+ {\r
+ if (!impl) return xpath_string();\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ if (setjmp(sd.error_handler)) return xpath_string();\r
+ #endif\r
+\r
+ xpath_context c(n, 1, 1);\r
+\r
+ return impl->root->eval_string(c, sd.stack);\r
+ }\r
+PUGI__NS_END\r
+\r
+namespace pugi\r
+{\r
+#ifndef PUGIXML_NO_EXCEPTIONS\r
+ PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_)\r
+ {\r
+ assert(_result.error);\r
+ }\r
+ \r
+ PUGI__FN const char* xpath_exception::what() const throw()\r
+ {\r
+ return _result.error;\r
+ }\r
+\r
+ PUGI__FN const xpath_parse_result& xpath_exception::result() const\r
+ {\r
+ return _result;\r
+ }\r
+#endif\r
+ \r
+ PUGI__FN xpath_node::xpath_node()\r
+ {\r
+ }\r
+ \r
+ PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_)\r
+ {\r
+ }\r
+ \r
+ PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xml_node xpath_node::node() const\r
+ {\r
+ return _attribute ? xml_node() : _node;\r
+ }\r
+ \r
+ PUGI__FN xml_attribute xpath_node::attribute() const\r
+ {\r
+ return _attribute;\r
+ }\r
+ \r
+ PUGI__FN xml_node xpath_node::parent() const\r
+ {\r
+ return _attribute ? _node : _node.parent();\r
+ }\r
+\r
+ PUGI__FN static void unspecified_bool_xpath_node(xpath_node***)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const\r
+ {\r
+ return (_node || _attribute) ? unspecified_bool_xpath_node : 0;\r
+ }\r
+ \r
+ PUGI__FN bool xpath_node::operator!() const\r
+ {\r
+ return !(_node || _attribute);\r
+ }\r
+\r
+ PUGI__FN bool xpath_node::operator==(const xpath_node& n) const\r
+ {\r
+ return _node == n._node && _attribute == n._attribute;\r
+ }\r
+ \r
+ PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const\r
+ {\r
+ return _node != n._node || _attribute != n._attribute;\r
+ }\r
+\r
+#ifdef __BORLANDC__\r
+ PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs && rhs;\r
+ }\r
+\r
+ PUGI__FN bool operator||(const xpath_node& lhs, bool rhs)\r
+ {\r
+ return (bool)lhs || rhs;\r
+ }\r
+#endif\r
+\r
+ PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_)\r
+ {\r
+ assert(begin_ <= end_);\r
+\r
+ size_t size_ = static_cast<size_t>(end_ - begin_);\r
+\r
+ if (size_ <= 1)\r
+ {\r
+ // deallocate old buffer\r
+ if (_begin != &_storage) impl::xml_memory::deallocate(_begin);\r
+\r
+ // use internal buffer\r
+ if (begin_ != end_) _storage = *begin_;\r
+\r
+ _begin = &_storage;\r
+ _end = &_storage + size_;\r
+ }\r
+ else\r
+ {\r
+ // make heap copy\r
+ xpath_node* storage = static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node)));\r
+\r
+ if (!storage)\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ return;\r
+ #else\r
+ throw std::bad_alloc();\r
+ #endif\r
+ }\r
+\r
+ memcpy(storage, begin_, size_ * sizeof(xpath_node));\r
+ \r
+ // deallocate old buffer\r
+ if (_begin != &_storage) impl::xml_memory::deallocate(_begin);\r
+\r
+ // finalize\r
+ _begin = storage;\r
+ _end = storage + size_;\r
+ }\r
+ }\r
+\r
+ PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(&_storage), _end(&_storage)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_), _begin(&_storage), _end(&_storage)\r
+ {\r
+ _assign(begin_, end_);\r
+ }\r
+\r
+ PUGI__FN xpath_node_set::~xpath_node_set()\r
+ {\r
+ if (_begin != &_storage) impl::xml_memory::deallocate(_begin);\r
+ }\r
+ \r
+ PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(ns._type), _begin(&_storage), _end(&_storage)\r
+ {\r
+ _assign(ns._begin, ns._end);\r
+ }\r
+ \r
+ PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns)\r
+ {\r
+ if (this == &ns) return *this;\r
+ \r
+ _type = ns._type;\r
+ _assign(ns._begin, ns._end);\r
+\r
+ return *this;\r
+ }\r
+\r
+ PUGI__FN xpath_node_set::type_t xpath_node_set::type() const\r
+ {\r
+ return _type;\r
+ }\r
+ \r
+ PUGI__FN size_t xpath_node_set::size() const\r
+ {\r
+ return _end - _begin;\r
+ }\r
+ \r
+ PUGI__FN bool xpath_node_set::empty() const\r
+ {\r
+ return _begin == _end;\r
+ }\r
+ \r
+ PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const\r
+ {\r
+ assert(index < size());\r
+ return _begin[index];\r
+ }\r
+\r
+ PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const\r
+ {\r
+ return _begin;\r
+ }\r
+ \r
+ PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const\r
+ {\r
+ return _end;\r
+ }\r
+ \r
+ PUGI__FN void xpath_node_set::sort(bool reverse)\r
+ {\r
+ _type = impl::xpath_sort(_begin, _end, _type, reverse);\r
+ }\r
+\r
+ PUGI__FN xpath_node xpath_node_set::first() const\r
+ {\r
+ return impl::xpath_first(_begin, _end, _type);\r
+ }\r
+\r
+ PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xpath_parse_result::operator bool() const\r
+ {\r
+ return error == 0;\r
+ }\r
+\r
+ PUGI__FN const char* xpath_parse_result::description() const\r
+ {\r
+ return error ? error : "No error";\r
+ }\r
+\r
+ PUGI__FN xpath_variable::xpath_variable(): _type(xpath_type_none), _next(0)\r
+ {\r
+ }\r
+\r
+ PUGI__FN const char_t* xpath_variable::name() const\r
+ {\r
+ switch (_type)\r
+ {\r
+ case xpath_type_node_set:\r
+ return static_cast<const impl::xpath_variable_node_set*>(this)->name;\r
+\r
+ case xpath_type_number:\r
+ return static_cast<const impl::xpath_variable_number*>(this)->name;\r
+\r
+ case xpath_type_string:\r
+ return static_cast<const impl::xpath_variable_string*>(this)->name;\r
+\r
+ case xpath_type_boolean:\r
+ return static_cast<const impl::xpath_variable_boolean*>(this)->name;\r
+\r
+ default:\r
+ assert(!"Invalid variable type");\r
+ return 0;\r
+ }\r
+ }\r
+\r
+ PUGI__FN xpath_value_type xpath_variable::type() const\r
+ {\r
+ return _type;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable::get_boolean() const\r
+ {\r
+ return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false;\r
+ }\r
+\r
+ PUGI__FN double xpath_variable::get_number() const\r
+ {\r
+ return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan();\r
+ }\r
+\r
+ PUGI__FN const char_t* xpath_variable::get_string() const\r
+ {\r
+ const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0;\r
+ return value ? value : PUGIXML_TEXT("");\r
+ }\r
+\r
+ PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const\r
+ {\r
+ return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable::set(bool value)\r
+ {\r
+ if (_type != xpath_type_boolean) return false;\r
+\r
+ static_cast<impl::xpath_variable_boolean*>(this)->value = value;\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable::set(double value)\r
+ {\r
+ if (_type != xpath_type_number) return false;\r
+\r
+ static_cast<impl::xpath_variable_number*>(this)->value = value;\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable::set(const char_t* value)\r
+ {\r
+ if (_type != xpath_type_string) return false;\r
+\r
+ impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this);\r
+\r
+ // duplicate string\r
+ size_t size = (impl::strlength(value) + 1) * sizeof(char_t);\r
+\r
+ char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size));\r
+ if (!copy) return false;\r
+\r
+ memcpy(copy, value, size);\r
+\r
+ // replace old string\r
+ if (var->value) impl::xml_memory::deallocate(var->value);\r
+ var->value = copy;\r
+\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable::set(const xpath_node_set& value)\r
+ {\r
+ if (_type != xpath_type_node_set) return false;\r
+\r
+ static_cast<impl::xpath_variable_node_set*>(this)->value = value;\r
+ return true;\r
+ }\r
+\r
+ PUGI__FN xpath_variable_set::xpath_variable_set()\r
+ {\r
+ for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _data[i] = 0;\r
+ }\r
+\r
+ PUGI__FN xpath_variable_set::~xpath_variable_set()\r
+ {\r
+ for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)\r
+ {\r
+ xpath_variable* var = _data[i];\r
+\r
+ while (var)\r
+ {\r
+ xpath_variable* next = var->_next;\r
+\r
+ impl::delete_xpath_variable(var->_type, var);\r
+\r
+ var = next;\r
+ }\r
+ }\r
+ }\r
+\r
+ PUGI__FN xpath_variable* xpath_variable_set::find(const char_t* name) const\r
+ {\r
+ const size_t hash_size = sizeof(_data) / sizeof(_data[0]);\r
+ size_t hash = impl::hash_string(name) % hash_size;\r
+\r
+ // look for existing variable\r
+ for (xpath_variable* var = _data[hash]; var; var = var->_next)\r
+ if (impl::strequal(var->name(), name))\r
+ return var;\r
+\r
+ return 0;\r
+ }\r
+\r
+ PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type)\r
+ {\r
+ const size_t hash_size = sizeof(_data) / sizeof(_data[0]);\r
+ size_t hash = impl::hash_string(name) % hash_size;\r
+\r
+ // look for existing variable\r
+ for (xpath_variable* var = _data[hash]; var; var = var->_next)\r
+ if (impl::strequal(var->name(), name))\r
+ return var->type() == type ? var : 0;\r
+\r
+ // add new variable\r
+ xpath_variable* result = impl::new_xpath_variable(type, name);\r
+\r
+ if (result)\r
+ {\r
+ result->_type = type;\r
+ result->_next = _data[hash];\r
+\r
+ _data[hash] = result;\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value)\r
+ {\r
+ xpath_variable* var = add(name, xpath_type_boolean);\r
+ return var ? var->set(value) : false;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable_set::set(const char_t* name, double value)\r
+ {\r
+ xpath_variable* var = add(name, xpath_type_number);\r
+ return var ? var->set(value) : false;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value)\r
+ {\r
+ xpath_variable* var = add(name, xpath_type_string);\r
+ return var ? var->set(value) : false;\r
+ }\r
+\r
+ PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value)\r
+ {\r
+ xpath_variable* var = add(name, xpath_type_node_set);\r
+ return var ? var->set(value) : false;\r
+ }\r
+\r
+ PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name)\r
+ {\r
+ return find(name);\r
+ }\r
+\r
+ PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const\r
+ {\r
+ return find(name);\r
+ }\r
+\r
+ PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0)\r
+ {\r
+ impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create();\r
+\r
+ if (!qimpl)\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ _result.error = "Out of memory";\r
+ #else\r
+ throw std::bad_alloc();\r
+ #endif\r
+ }\r
+ else\r
+ {\r
+ impl::buffer_holder impl_holder(qimpl, impl::xpath_query_impl::destroy);\r
+\r
+ qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result);\r
+\r
+ if (qimpl->root)\r
+ {\r
+ _impl = static_cast<impl::xpath_query_impl*>(impl_holder.release());\r
+ _result.error = 0;\r
+ }\r
+ }\r
+ }\r
+\r
+ PUGI__FN xpath_query::~xpath_query()\r
+ {\r
+ impl::xpath_query_impl::destroy(_impl);\r
+ }\r
+\r
+ PUGI__FN xpath_value_type xpath_query::return_type() const\r
+ {\r
+ if (!_impl) return xpath_type_none;\r
+\r
+ return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype();\r
+ }\r
+\r
+ PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const\r
+ {\r
+ if (!_impl) return false;\r
+ \r
+ impl::xpath_context c(n, 1, 1);\r
+ impl::xpath_stack_data sd;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ if (setjmp(sd.error_handler)) return false;\r
+ #endif\r
+ \r
+ return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack);\r
+ }\r
+ \r
+ PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const\r
+ {\r
+ if (!_impl) return impl::gen_nan();\r
+ \r
+ impl::xpath_context c(n, 1, 1);\r
+ impl::xpath_stack_data sd;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ if (setjmp(sd.error_handler)) return impl::gen_nan();\r
+ #endif\r
+\r
+ return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack);\r
+ }\r
+\r
+#ifndef PUGIXML_NO_STL\r
+ PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const\r
+ {\r
+ impl::xpath_stack_data sd;\r
+\r
+ return impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd).c_str();\r
+ }\r
+#endif\r
+\r
+ PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const\r
+ {\r
+ impl::xpath_stack_data sd;\r
+\r
+ impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd);\r
+\r
+ size_t full_size = r.length() + 1;\r
+ \r
+ if (capacity > 0)\r
+ {\r
+ size_t size = (full_size < capacity) ? full_size : capacity;\r
+ assert(size > 0);\r
+\r
+ memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t));\r
+ buffer[size - 1] = 0;\r
+ }\r
+ \r
+ return full_size;\r
+ }\r
+\r
+ PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const\r
+ {\r
+ if (!_impl) return xpath_node_set();\r
+\r
+ impl::xpath_ast_node* root = static_cast<impl::xpath_query_impl*>(_impl)->root;\r
+\r
+ if (root->rettype() != xpath_type_node_set)\r
+ {\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ return xpath_node_set();\r
+ #else\r
+ xpath_parse_result res;\r
+ res.error = "Expression does not evaluate to node set";\r
+\r
+ throw xpath_exception(res);\r
+ #endif\r
+ }\r
+ \r
+ impl::xpath_context c(n, 1, 1);\r
+ impl::xpath_stack_data sd;\r
+\r
+ #ifdef PUGIXML_NO_EXCEPTIONS\r
+ if (setjmp(sd.error_handler)) return xpath_node_set();\r
+ #endif\r
+\r
+ impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack);\r
+\r
+ return xpath_node_set(r.begin(), r.end(), r.type());\r
+ }\r
+\r
+ PUGI__FN const xpath_parse_result& xpath_query::result() const\r
+ {\r
+ return _result;\r
+ }\r
+\r
+ PUGI__FN static void unspecified_bool_xpath_query(xpath_query***)\r
+ {\r
+ }\r
+\r
+ PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const\r
+ {\r
+ return _impl ? unspecified_bool_xpath_query : 0;\r
+ }\r
+\r
+ PUGI__FN bool xpath_query::operator!() const\r
+ {\r
+ return !_impl;\r
+ }\r
+\r
+ PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const\r
+ {\r
+ xpath_query q(query, variables);\r
+ return select_single_node(q);\r
+ }\r
+\r
+ PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const\r
+ {\r
+ xpath_node_set s = query.evaluate_node_set(*this);\r
+ return s.empty() ? xpath_node() : s.first();\r
+ }\r
+\r
+ PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const\r
+ {\r
+ xpath_query q(query, variables);\r
+ return select_nodes(q);\r
+ }\r
+\r
+ PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const\r
+ {\r
+ return query.evaluate_node_set(*this);\r
+ }\r
+}\r
+\r
+#endif\r
+\r
+#ifdef __BORLANDC__\r
+# pragma option pop\r
+#endif\r
+\r
+// Intel C++ does not properly keep warning state for function templates,\r
+// so popping warning state at the end of translation unit leads to warnings in the middle.\r
+#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)\r
+# pragma warning(pop)\r
+#endif\r
+\r
+// Undefine all local macros (makes sure we're not leaking macros in header-only mode)\r
+#undef PUGI__NO_INLINE\r
+#undef PUGI__STATIC_ASSERT\r
+#undef PUGI__DMC_VOLATILE\r
+#undef PUGI__MSVC_CRT_VERSION\r
+#undef PUGI__NS_BEGIN\r
+#undef PUGI__NS_END\r
+#undef PUGI__FN\r
+#undef PUGI__FN_NO_INLINE\r
+#undef PUGI__IS_CHARTYPE_IMPL\r
+#undef PUGI__IS_CHARTYPE\r
+#undef PUGI__IS_CHARTYPEX\r
+#undef PUGI__SKIPWS\r
+#undef PUGI__OPTSET\r
+#undef PUGI__PUSHNODE\r
+#undef PUGI__POPNODE\r
+#undef PUGI__SCANFOR\r
+#undef PUGI__SCANWHILE\r
+#undef PUGI__ENDSEG\r
+#undef PUGI__THROW_ERROR\r
+#undef PUGI__CHECK_ERROR\r
+\r
+#endif\r
+\r
+/**\r
+ * Copyright (c) 2006-2014 Arseny Kapoulkine\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person\r
+ * obtaining a copy of this software and associated documentation\r
+ * files (the "Software"), to deal in the Software without\r
+ * restriction, including without limitation the rights to use,\r
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+ * copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following\r
+ * conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be\r
+ * included in all copies or substantial portions of the Software.\r
+ * \r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r
+ * OTHER DEALINGS IN THE SOFTWARE.\r
+ */\r