-
Notifications
You must be signed in to change notification settings - Fork 540
/
Copy pathrapidxml_wrap.hpp
777 lines (663 loc) · 22.8 KB
/
rapidxml_wrap.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
#pragma once
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
#include "StringUtil.h"
#include "FileUtil.h"
#include <string>
#include <sstream>
#include <ostream>
#include <fstream>
#include <vector>
#include <stdexcept>
#include <utility>
#include <memory>
#include <functional>
#include <assert.h>
namespace acut
{
template <typename T>
struct default_delete
{
void operator()( T* t )
{
delete t;
}
};
template <typename T>
struct noop_delete
{
void operator()( T* )
{ }
};
/*
* Examples:
* Reading:
* // we are using xml_key_error exceptions
* acut::XmlDoc<char> xml(true);
*
* // parse file and throw on any errors
* xml.read_from_file(L"path/to/document.xml");
*
* // disable xml_key_error exceptions because we don't care if some values do not exist
* xml.use_exceptions(false);
*
* // read simple string
* auto some_string = xml.get<std::string>("XmlConfig.Section1.<Attribute1>");
*
* // capturing size by the template parameter
* char buffer[256];
* xml.get("XmlConfig.Section1.SomeData", buffer);
*
* // providing size manually
* char* buffer_ptr = new char[256];
* xml.get("XmlConfig.Section2.SomeData2", buffer_ptr, 256);
*
* // reading and converting a double
* auto d = xml.get<double>("XmlConfig.Section3.<DoubleAttribute>");
*
* // reading and converting some arbitrary type that overloads std::operator>>()
* auto d = xml.get<MyCustomType>("XmlConfig.Section3.Value");
*
* Writing:
* // we are using exception for now
* acut::XmlDoc<char> xml(true);
*
* // create empty document
* xml.create_document();
*
* // write some string
* // std::string some_string;
* xml.set("XmlConfig.Section1.<Attribute1>", some_string);
*
* // leaving the size to be deternimed automatically by null-terminator
* char buffer[256];
* xml.set("XmlConfig.Section1.SomeData", buffer);
*
* // providing size manually
* // char buffer2[256];
* xml.set("XmlConfig.Section2.SomeData2", buffer2, 256);
*
* // writing a double
* // double some_d;
* xml.set("XmlConfig.Section3.<DoubleAttribute>", some_d);
*
* // reading and converting some arbitrary type that overloads std::operator<<()
* auto d = xml.get<MyCustomType>("XmlConfig.Section3.Value");
*
* // write document to a file
* xml.write_document(L"path/to/file.xml");
*/
template <typename Ch>
class XmlDoc;
template <typename Ch>
class XmlIter;
template <typename Ch>
class XmlRange;
struct xml_error : public std::runtime_error
{
explicit xml_error(const char* msg) : std::runtime_error(msg) {}
explicit xml_error(const std::string& msg) : std::runtime_error(msg) {}
};
struct xml_key_error : public xml_error
{
explicit xml_key_error(const char* msg) : xml_error(msg) {}
explicit xml_key_error(const std::string& msg) : xml_error(msg) {}
};
struct xml_general_error : public xml_error
{
explicit xml_general_error(const char* msg) : xml_error(msg) {}
explicit xml_general_error(const std::string& msg) : xml_error(msg) {}
};
template<typename Ch = char>
class XmlWrap
{
public:
typedef rapidxml::xml_document<Ch> xml_document;
typedef rapidxml::xml_node<Ch> xml_node;
typedef rapidxml::xml_attribute<Ch> xml_attribute;
typedef std::basic_string<Ch> string_t;
typedef std::unique_ptr<xml_document, std::function<void(xml_document*)>> xml_ptr;
template<typename T> struct type { };
/*
* Get value by key. Key has the form "ElementName1.ElementName2.ElementNameN
* or "ElementName1.ElementName2.<AttributeName>".
* If T is int, long long, unsigned long long or double, tries to convert
* the value to this type and throws acut::xml_general_error if conversino failes.
* Otherwise, uses std::operator>>() to read and return the value
* of type T.
* Throws acut::xml_general_error if XML document is not initialized or value
* can't be converted and acut::xml_key_error if key is empty or does not exist.
*/
template <typename T>
T get(const string_t& key)
{
try
{
return get_helper(key, type<T>());
}
catch (const std::logic_error& ex)
{
if (!*noex_)
throw xml_general_error(std::string("Failed to convert value: ") + ex.what());
return T();
}
catch (const xml_key_error&)
{
if (!*noex_) throw;
return T();
}
}
/*
* Check if 'key' is valid
*/
bool has(const string_t& key)
{
try
{
find_node(key);
return true;
}
catch (const std::exception&)
{
return false;
}
}
/*
* Assign to 'dest' the value stored under the 'key', or leave value unchanged on errors.
*/
template <typename T>
void get_if_present(const string_t& key, T& dest)
{
try
{
dest = get_helper(key, type<T>());
}
catch (const std::logic_error&)
{
}
catch (const xml_key_error&)
{
}
}
/*
* Get for c-style strings.
* Throws: same as usual get() function.
*/
template <size_t N>
bool get(const string_t& key, Ch (&dest)[N])
{
return get(key, dest, N);
}
/*
* Get for pointers to c-style strings.
* Throws: same as usual get() function + acut::xml_general_error if dest_size is not
* enough to store found value.
*/
bool get(const string_t& key, Ch* dest, int dest_size)
{
try
{
assert(dest_size > 0);
auto pair = find_value(key);
if (static_cast<size_t>(dest_size) <= pair.second)
throw xml_general_error("Destination buffer is too small");
memcpy(dest, pair.first, pair.second * sizeof(Ch));
dest[pair.second] = acut::ensure_tchar<Ch>('\0');
return true;
}
catch (const xml_key_error&)
{
if (!*noex_) throw;
return false;
}
}
/*
* Set the value of the key. Keys are same as in get() function.
* If any of the leaf or intermediate nodes do not exist, they are created.
* Uses std::operator<<() to convert the argument to string.
* Throws acut::xml_general_error if XML document is not initialized and
* acut::xml_key_error if key is empty.
*/
template <typename T>
bool set(const string_t& key, const T& value)
{
return set_helper(key, value);
}
/*
* Set for pointers to c-style strings. If dest_size == 0, length is
* calculated automatically, so string should be null-terminated.
* Throws: same as usual get() function.
*/
bool set(const string_t& key, const Ch* value, int dest_size = 0)
{
create_value(key, value, dest_size);
return true;
}
/*
* Returns iterator that iterates over the children of the node, specified by 'key'.
*/
XmlRange<Ch> all_children_of(const string_t& key);
/*
* Returns iterator that iterates over the nodes, specified by 'key', with the same name.
*/
XmlRange<Ch> all_nodes_named(const string_t& key);
/*
* Append a node and return a handle to it.
*/
XmlWrap<Ch> append(const string_t& key)
{
auto node = create_or_find_node(key, true);
return XmlWrap<Ch>(doc_, noex_, node);
}
string_t name()
{
return string_t(node_->name(), node_->name_size());
}
string_t value()
{
return string_t( node_->value() );
}
void value(const string_t& val)
{
node_->value(val.c_str());
}
private:
class Path
{
public:
Path(const string_t& key)
{
acut::split(key, &path_, acut::ensure_tchar<Ch>("."));
if (path_.size() == 0)
last_is_attribute_ = false;
else
last_is_attribute_ = (path_.back().front() == acut::ensure_tchar<Ch>('<') &&
path_.back().back() == acut::ensure_tchar<Ch>('>') );
}
const string_t& operator[](size_t index) const
{
return path_[index];
}
const string_t& back() const
{
return path_.back();
}
bool is_attribute() const
{
return last_is_attribute_;
}
size_t size() const
{
return path_.size();
}
private:
std::vector<string_t> path_;
bool last_is_attribute_;
};
XmlWrap(xml_ptr* doc, bool* noex, xml_node* current)
: doc_(doc)
, noex_(noex)
, node_(current)
{ }
void set_current(xml_node* current)
{
node_ = current;
}
template <typename T>
T get_helper(const string_t& key, type<T>)
{
T res;
std::basic_istringstream<Ch> iss((get_helper(key, type<string_t>())));
iss >> res;
return res;
}
string_t get_helper(const string_t& key, type<string_t>)
{
auto pair = find_value(key);
return string_t(pair.first, pair.second);
}
int get_helper(const string_t& key, type<int>)
{ return std::stoi(get_helper(key, type<string_t>())); }
long long get_helper(const string_t& key, type<long long>)
{ return std::stoll(get_helper(key, type<string_t>())); }
unsigned long long get_helper(const string_t& key, type<unsigned long long>)
{ return std::stoull(get_helper(key, type<string_t>())); }
double get_helper(const string_t& key, type<double>)
{ return std::stod(get_helper(key, type<string_t>())); }
template <typename T>
bool set_helper(const string_t& key, const T& value)
{
std::basic_ostringstream<Ch> oss;
oss << value;
auto data = oss.str();
create_value(key, data.c_str(), data.size());
return true;
}
bool set_helper(const string_t& key, const string_t& value)
{
create_value(key, value.c_str(), value.size());
return true;
}
// Path is implicitly convertibale from string
std::pair<Ch*, size_t> find_value(const Path& key)
{
xml_node* node = find_node(key);
if (key.is_attribute())
{
auto attr_name = key.back().substr(1, key.back().size() - 2);
auto attr = node->first_attribute(attr_name.c_str(), attr_name.size());
if (!attr)
throw xml_key_error("No such attribute '" + acut::ensure_tchar<char>(attr_name.c_str()) + "'");
return std::make_pair(attr->value(), attr->value_size());
}
else
{
return std::make_pair(node->value(), node->value_size());
}
}
// Path is implicitly convertibale from string
xml_node* find_node(const Path& key)
{
if (!get_doc())
throw xml_general_error("XML document is not initialized");
assert(node_);
xml_node* node = node_;
for (size_t i = 0; i < key.size() - (key.is_attribute() ? 1 : 0); ++i)
{
node = node->first_node(key[i].c_str(), key[i].size());
if (!node)
throw xml_key_error("No such node '" + acut::ensure_tchar<char>(key[i].c_str()) + "'");
}
return node;
}
xml_node* create_or_find_node(const Path& key, bool always_create = false)
{
if (!get_doc())
throw xml_general_error("XML document is not initialized");
assert(node_);
xml_node* node = node_;
size_t total = key.size() - (key.is_attribute() ? 1 : 0);
for (size_t i = 0; i < total; ++i)
{
auto found_node = node->first_node(key[i].c_str(), key[i].size());
if (!found_node || (i == total - 1 && always_create))
{
auto name = get_doc()->allocate_string(key[i].c_str(), key[i].size());
auto new_node = get_doc()->allocate_node(rapidxml::node_element, name, nullptr, key[i].size());
node->append_node(new_node);
node = new_node;
}
else
{
node = found_node;
}
}
return node;
}
void create_value(const Path& key, const Ch* value, size_t value_size)
{
xml_node* node = create_or_find_node(key);
if (value_size == 0)
value_size = rapidxml::internal::measure(value);
auto allocated_data = get_doc()->allocate_string(value, value_size);
if (key.is_attribute())
{
auto attr_name = key.back().substr(1, key.back().size() - 2);
auto attr = node->first_attribute(attr_name.c_str(), attr_name.size());
if (!attr)
{
auto name = get_doc()->allocate_string(attr_name.c_str(), attr_name.size());
auto new_attr = get_doc()->allocate_attribute(name, allocated_data, attr_name.size(), value_size);
node->append_attribute(new_attr);
}
else
{
attr->value(allocated_data, value_size);
}
}
else
{
node->value(allocated_data, value_size);
}
}
xml_document* get_doc()
{
return doc_->get();
}
friend class XmlDoc<Ch>;
friend class XmlIter<Ch>;
xml_ptr* doc_;
bool* noex_;
xml_node* node_;
};
template <typename Ch>
class XmlIter
{
public:
XmlIter& operator++()
{
if (!name_.empty())
node_ = node_->next_sibling(name_.c_str(), name_.size());
else
node_ = node_->next_sibling();
return *this;
}
bool operator!=(const XmlIter<Ch>& snd) const
{
return node_ != snd.node_;
}
XmlWrap<Ch> operator*()
{
return XmlWrap<Ch>(doc_, noex_, node_);
}
private:
XmlIter()
: node_(nullptr)
, doc_(nullptr)
, noex_(nullptr)
{ }
XmlIter(typename XmlWrap<Ch>::string_t name,
typename XmlWrap<Ch>::xml_node* node,
typename XmlWrap<Ch>::xml_ptr* doc,
bool* noex)
: name_(name)
, node_(node)
, doc_(doc)
, noex_(noex)
{ }
friend class XmlRange<Ch>;
typename XmlWrap<Ch>::string_t name_;
typename XmlWrap<Ch>::xml_node* node_;
typename XmlWrap<Ch>::xml_ptr* doc_;
bool* noex_;
};
template <typename Ch>
class XmlRange
{
public:
XmlIter<Ch> begin()
{
return XmlIter<Ch>(name_, node_, doc_, noex_);
}
XmlIter<Ch> end()
{
return XmlIter<Ch>();
}
private:
XmlRange(typename XmlWrap<Ch>::string_t name,
typename XmlWrap<Ch>::xml_node* node,
typename XmlWrap<Ch>::xml_ptr* doc,
bool* noex)
: name_(name)
, node_(node)
, doc_(doc)
, noex_(noex)
{ }
friend class XmlWrap<Ch>;
typename XmlWrap<Ch>::string_t name_;
typename XmlWrap<Ch>::xml_node* node_;
typename XmlWrap<Ch>::xml_ptr* doc_;
bool* noex_;
};
template <typename Ch>
class XmlDoc : public XmlWrap<Ch>
{
public:
typedef typename XmlWrap<Ch>::xml_document xml_document;
typedef typename XmlWrap<Ch>::string_t string_t;
typedef typename XmlWrap<Ch>::xml_ptr xml_ptr;
/*
* Create non-initialized XML document.
*/
explicit XmlDoc(bool use_except = true)
: XmlWrap<Ch>(&doc_, &noex_, nullptr)
, noex_(!use_except)
, doc_(nullptr, acut::noop_delete<xml_document>())
, buffer_()
{}
/*
* Read XML document from file.
* Throws std::runtime_error if couldn't read the file or acut::xml_general_error if
* errors were encountered while parsing the file.
*/
void read_from_file(const std::wstring& filename);
/*
* Read XML document from string.
*/
void read_from_string(const string_t& content)
{
doc_ = xml_ptr(new xml_document, acut::default_delete<xml_document>());
buffer_.assign(std::begin(content), std::end(content));
parse_buffer(&buffer_[0]);
XmlWrap<Ch>::set_current(doc_.get());
}
/*
* Read XML document from buffer.
* buffer - null-terminated buffer with XML content. It will be modified by the parser.
*/
void read_from_buffer(Ch* buffer)
{
doc_ = xml_ptr(new xml_document, acut::default_delete<xml_document>());
parse_buffer(buffer);
XmlWrap<Ch>::set_current(doc_.get());
}
/*
* Use provided xml_document.
* own - set whether to own the document or not
*/
void use_document(xml_document* doc, bool own = false)
{
if (own)
doc_ = xml_ptr(doc, acut::default_delete<xml_document>());
else
doc_ = xml_ptr(doc, acut::noop_delete<xml_document>());
XmlWrap<Ch>::set_current(doc_.get());
}
/*
* Create empty XML document.
*/
void create_document()
{
doc_ = xml_ptr(new xml_document, acut::default_delete<xml_document>());
XmlWrap<Ch>::set_current(doc_.get());
}
/*
* Write document to stream.
* Throws acut::xml_general_error if XML document is not initialized.
*/
template<class CharT, class Traits>
void write_document(std::basic_ostream<CharT, Traits>& os)
{
if (!doc_)
throw xml_general_error("XML document is not initialized");
os << *doc_;
}
/*
* Write document to file with name 'filename', overwriting it.
* Throws acut::xml_general_error if XML document is not initialized.
*/
void write_document(const std::wstring& filename)
{
if (!doc_)
throw xml_general_error("XML document is not initialized");
std::basic_stringstream<Ch> output;
output << *doc_;
std::ofstream outfile(filename);
std::string utf8_string = acut::ensure_tchar<char>(output.str().c_str());
outfile.write(utf8_string.c_str(), utf8_string.size());
outfile.close();
}
/*
* Set whether to use exceptions or return bool values to indicate failure.
*/
void use_exceptions(bool use_except)
{
noex_ = !use_except;
}
bool use_exceptions() const
{
return !noex_;
}
private:
void parse_buffer(Ch* buffer)
{
doc_->template parse<rapidxml::parse_no_data_nodes>(buffer);
}
bool noex_;
xml_ptr doc_;
std::basic_string<Ch> buffer_;
};
// Path is implicitly convertible from string
template <typename Ch>
XmlRange<Ch> XmlWrap<Ch>::all_children_of(const string_t& key)
{
Path path(key);
if (path.is_attribute())
throw xml_key_error("Can't iterate attributes");
auto first_child = find_node(path)->first_node();
return XmlRange<Ch>(string_t(), first_child, doc_, noex_);
}
// Path is implicitly convertible from string
template <typename Ch>
XmlRange<Ch> XmlWrap<Ch>::all_nodes_named(const string_t& key)
{
Path path(key);
if (path.is_attribute())
throw xml_key_error("Can't iterate attributes");
return XmlRange<Ch>(path.back(), find_node(path), doc_, noex_);
}
template <>
inline void XmlDoc<char>::read_from_file(const std::wstring& filename)
{
try
{
doc_ = xml_ptr(new xml_document, acut::default_delete<xml_document>());
if (!acut::read_file(filename, buffer_))
throw std::runtime_error("Failed to read file: " + acut::ensure_tchar<char>(filename.c_str()));
parse_buffer(&buffer_[0]);
XmlWrap<char>::set_current(doc_.get());
}
catch (const rapidxml::parse_error& ex)
{
throw xml_general_error("Error parsing file '" + acut::ensure_tchar<char>(filename.c_str()) + "': " + ex.what());
}
}
template <>
inline void XmlDoc<wchar_t>::read_from_file(const std::wstring& filename)
{
try
{
doc_ = xml_ptr(new xml_document, acut::default_delete<xml_document>());
std::string utf8_content;
if (!acut::read_file(filename, utf8_content))
throw std::runtime_error("Failed to read file: " + acut::ensure_tchar<char>(filename.c_str()));
buffer_ = blackbone::Utils::UTF8ToWstring( utf8_content );
parse_buffer(&buffer_[0]);
XmlWrap<wchar_t>::set_current(doc_.get());
}
catch (const rapidxml::parse_error& ex)
{
throw xml_general_error("Error parsing file '" + acut::ensure_tchar<char>(filename.c_str()) + "': " + ex.what());
}
}
}