The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
simple_wml.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2008 - 2025
3 by David White <dave@whitevine.net>
4 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY.
12
13 See the COPYING file for more details.
14*/
15
16#include <sstream>
17
18#include <boost/iostreams/copy.hpp>
19#include <boost/iostreams/filtering_stream.hpp>
20#include <boost/iostreams/filter/bzip2.hpp>
21#include <boost/iostreams/filter/counter.hpp>
22#include <boost/iostreams/filter/gzip.hpp>
23
25
26#include "log.hpp"
28#include "utils/general.hpp"
29
30static lg::log_domain log_config("config");
31#define ERR_SWML LOG_STREAM(err, log_config)
32#define LOG_SWML LOG_STREAM(info, log_config)
33
34namespace simple_wml {
35
36std::size_t document::document_size_limit = 40000000;
37
38namespace {
39
40void debug_delete(node* n) {
41 delete n;
42}
43
44char* uncompress_buffer(const string_span& input, string_span* span)
45{
46 int nalloc = input.size();
47 int state = 0;
48 try {
49 std::istringstream stream(std::string(input.begin(), input.end()));
50 state = 1;
51 boost::iostreams::filtering_stream<boost::iostreams::input> filter;
52 state = 2;
53 if (!span->empty() && *span->begin() == 'B') {
54 filter.push(boost::iostreams::bzip2_decompressor());
55 } else {
56 filter.push(boost::iostreams::gzip_decompressor());
57 }
58 filter.push(stream);
59 state = 3;
60
61 const std::size_t chunk_size = std::min(input.size() * 10, document::document_size_limit);
62 nalloc = chunk_size;
63 std::vector<char> buf(chunk_size);
64 state = 4;
65 std::size_t len = 0;
66 std::size_t pos = 0;
67 while(filter.good() && (len = filter.read(&buf[pos], chunk_size).gcount()) == chunk_size) {
68 if(pos + chunk_size > document::document_size_limit) {
69 throw error("WML document exceeded size limit during decompression");
70 }
71
72 pos += len;
73 buf.resize(pos + chunk_size);
74 len = 0;
75 }
76
77 if(!filter.eof() && !filter.good()) {
78 throw error("failed to uncompress");
79 }
80
81 pos += len;
82 state = 5;
83 nalloc = pos;
84
85 buf.resize(pos);
86 state = 6;
87
88 char* small_out = new char[pos+1];
89 memcpy(small_out, &buf[0], pos);
90 state = 7;
91
92 small_out[pos] = 0;
93
94 *span = string_span(small_out, pos);
95 state = 8;
96 return small_out;
97 } catch (const std::bad_alloc& e) {
98 ERR_SWML << "ERROR: bad_alloc caught in uncompress_buffer() state "
99 << state << " alloc bytes " << nalloc << " with input: '"
100 << input << "' " << e.what();
101 throw error("Bad allocation request in uncompress_buffer().");
102 }
103}
104
105char* compress_buffer(const char* input, string_span* span, bool bzip2)
106{
107 int nalloc = strlen(input);
108 int state = 0;
109 try {
110 std::string in(input);
111 state = 1;
112 std::istringstream istream(in);
113 state = 2;
114 boost::iostreams::filtering_stream<boost::iostreams::output> filter;
115 state = 3;
116 if (bzip2) {
117 filter.push(boost::iostreams::bzip2_compressor());
118 } else {
119 filter.push(boost::iostreams::gzip_compressor());
120 }
121 state = 4;
122 nalloc = in.size()*2 + 80;
123 std::vector<char> buf(nalloc);
124 boost::iostreams::array_sink out(&buf[0], buf.size());
125 filter.push(boost::iostreams::counter());
126 filter.push(out);
127
128 state = 5;
129
130 boost::iostreams::copy(istream, filter, buf.size());
131 const int len = filter.component<boost::iostreams::counter>(1)->characters();
132 assert(len < 128*1024*1024);
133 if((!filter.eof() && !filter.good()) || len == static_cast<int>(buf.size())) {
134 throw error("failed to compress");
135 }
136 state = 6;
137 nalloc = len;
138
139 buf.resize(len);
140 state = 7;
141
142 char* small_out = new char[len];
143 memcpy(small_out, &buf[0], len);
144 state = 8;
145
146 *span = string_span(small_out, len);
147 assert(*small_out == (bzip2 ? 'B' : 31));
148 state = 9;
149 return small_out;
150 } catch (const std::bad_alloc& e) {
151 ERR_SWML << "ERROR: bad_alloc caught in compress_buffer() state "
152 << state << " alloc bytes " << nalloc << " with input: '"
153 << input << "' " << e.what();
154 throw error("Bad allocation request in compress_buffer().");
155 }
156}
157
158} // namespace
159
160bool string_span::to_bool(bool default_value) const
161{
162 if(empty()) {
163 return default_value;
164 }
165
166 if (operator==("no") || operator==("off") || operator==("false") || operator==("0") || operator==("0.0"))
167 return false;
168
169 return true;
170}
171
173{
174 const int buf_size = 64;
175 if(size() >= buf_size) {
176 return 0;
177 }
178 char buf[64];
179 memcpy(buf, begin(), size());
180 buf[size()] = 0;
181 return atoi(buf);
182}
183
184std::string string_span::to_string() const
185{
186 return std::string(begin(), end());
187}
188
190{
191 char* buf = new char[size() + 1];
192 memcpy(buf, begin(), size());
193 buf[size()] = 0;
194 return buf;
195}
196
197error::error(const char* msg)
198 : game::error(msg)
199{
200 ERR_SWML << "ERROR: '" << msg << "'";
201}
202
203std::ostream& operator<<(std::ostream& o, const string_span& s)
204{
205 o << std::string(s.begin(), s.end());
206 return o;
207}
208
209node::node(document& doc, node* parent) :
210 doc_(&doc),
211 attr_(),
212 parent_(parent),
213 children_(),
214 ordered_children_(),
215 output_cache_()
216{
217}
218
219#ifdef _MSC_VER
220#pragma warning (push)
221#pragma warning (disable: 4706)
222#endif
223node::node(document& doc, node* parent, const char** str, int depth) :
224 doc_(&doc),
225 attr_(),
226 parent_(parent),
227 children_(),
228 ordered_children_(),
229 output_cache_()
230{
231 if(depth >= 1000) {
232 throw error("elements nested too deep");
233 }
234
235 const char*& s = *str;
236
237 const char* const begin = s;
238 while(*s) {
239 switch(*s) {
240 case '[': {
241 if(s[1] == '/') {
242 output_cache_ = string_span(begin, s - begin);
243 s = strchr(s, ']');
244 if(s == nullptr) {
245 throw error("end element unterminated");
246 }
247
248 ++s;
249 return;
250 }
251
252 ++s;
253 const char* end = strchr(s, ']');
254 if(end == nullptr) {
255 throw error("unterminated element");
256 }
257
258 const int list_index = get_children(string_span(s, end - s));
259 if(children_[list_index].second.size() > std::numeric_limits<unsigned short>::max()) {
260 throw error("too many child elements");
261 }
262
263 s = end + 1;
264
266 children_[list_index].second.push_back(new node(doc, this, str, depth+1));
267 ordered_children_.emplace_back(list_index, children_[list_index].second.size() - 1);
269
270 break;
271 }
272 case ' ':
273 case '\t':
274 case '\n':
275 ++s;
276 break;
277 case '#':
278 s = strchr(s, '\n');
279 if(s == nullptr) {
280 throw error("did not find newline after '#'");
281 }
282 break;
283 default: {
284 const char* end = strchr(s, '=');
285 if(end == nullptr) {
286 ERR_SWML << "attribute: " << s;
287 throw error("did not find '=' after attribute");
288 }
289
290 string_span name(s, end - s);
291 s = end + 1;
292 if(*s == '_') {
293 s = strchr(s, '"');
294 if(s == nullptr) {
295 throw error("did not find '\"' after '_'");
296 }
297 }
298
299 if (*s != '"') {
300 end = strchr(s, '\n');
301 if (!end) {
302 ERR_SWML << "ATTR: '" << name << "' (((" << s << ")))";
303 throw error("did not find end of attribute");
304 }
305 if (memchr(s, '"', end - s))
306 throw error("found stray quotes in unquoted value");
307 goto read_attribute;
308 }
309 end = s;
310 while(true)
311 {
312 // Read until the first single double quote.
313 while((end = strchr(end+1, '"')) && end[1] == '"') {
314#ifdef _MSC_VER
315#pragma warning (pop)
316#endif
317 ++end;
318 }
319 if(end == nullptr)
320 throw error("did not find end of attribute");
321
322 // Stop if newline.
323 const char *endline = end + 1;
324 while (*endline == ' ') ++endline;
325 if (*endline == '\n') break;
326
327 // Read concatenation marker.
328 if (*(endline++) != '+')
329 throw error("did not find newline after end of attribute");
330 if (*(endline++) != '\n')
331 throw error("did not find newline after '+'");
332
333 // Read textdomain marker.
334 if (*endline == '#') {
335 endline = strchr(endline + 1, '\n');
336 if (!endline)
337 throw error("did not find newline after '#'");
338 ++endline;
339 }
340
341 // Read indentation and start of string.
342 while (*endline == '\t') ++endline;
343 if (*endline == '_') ++endline;
344 if (*endline != '"')
345 throw error("did not find quotes after '+'");
346 end = endline;
347 }
348
349 ++s;
350
351 read_attribute:
352 string_span value(s, end - s);
353 if(attr_.empty() == false && !(attr_.back().key < name)) {
354 ERR_SWML << "attributes: '" << attr_.back().key << "' < '" << name << "'";
355 throw error("attributes not in order");
356 }
357
358 s = end + 1;
359
360 attr_.emplace_back(name, value);
361 }
362 }
363 }
364
365 output_cache_ = string_span(begin, s - begin);
367}
368
370{
371 for(child_map::iterator i = children_.begin(); i != children_.end(); ++i) {
372 for(child_list::iterator j = i->second.begin(); j != i->second.end(); ++j) {
373 debug_delete(*j);
374 }
375 }
376}
377
378namespace {
379struct string_span_pair_comparer
380{
381 bool operator()(const string_span& a, const node::attribute& b) const {
382 return a < b.key;
383 }
384
385 bool operator()(const node::attribute& a, const string_span& b) const {
386 return a.key < b;
387 }
388
389 bool operator()(const node::attribute& a,
390 const node::attribute& b) const {
391 return a.key < b.key;
392 }
393};
394}
395
396const string_span& node::operator[](const char* key) const
397{
398 static string_span empty("");
399 string_span span(key);
400 auto range = std::equal_range(attr_.begin(), attr_.end(), span, string_span_pair_comparer());
401 if(range.first != range.second) {
402 return range.first->value;
403 }
404
405 return empty;
406}
407
408bool node::has_attr(const char* key) const
409{
410 string_span span(key);
411 auto range = std::equal_range(attr_.begin(), attr_.end(), span, string_span_pair_comparer());
412 return range.first != range.second;
413}
414
415node& node::set_attr(const char* key, const char* value)
416{
417 set_dirty();
418
419 string_span span(key);
420 auto range = std::equal_range(attr_.begin(), attr_.end(), span, string_span_pair_comparer());
421 if(range.first != range.second) {
422 range.first->value = string_span(value);
423 } else {
424 attr_.insert(range.first, attribute(span, string_span(value)));
425 }
426
427 return *this;
428}
429
430node& node::set_attr_dup(const char* key, const char* value)
431{
432 return set_attr(key, doc_->dup_string(value));
433}
434
435node& node::set_attr_dup(const char* key, const string_span& value)
436{
437 char* buf = value.duplicate();
439 return set_attr(key, buf);
440}
441
443{
444 return set_attr(key, doc_->esc_string(value));
445}
446
447node& node::set_attr_int(const char* key, int value)
448{
449 std::string temp = std::to_string(value);
450 return set_attr_dup(key, temp.c_str());
451}
452
453node& node::add_child_at(const char* name, std::size_t index)
454{
455 set_dirty();
456
457 const int list_index = get_children(name);
458 child_list& list = children_[list_index].second;
459 if(list.size() > std::numeric_limits<unsigned short>::max()) {
460 throw error("too many child elements");
461 }
462 if(index > list.size()) {
463 index = list.size();
464 }
465
467 list.insert(list.begin() + index, new node(*doc_, this));
468 insert_ordered_child(list_index, index);
469
471 return *list[index];
472}
473
474
475node& node::add_child(const char* name)
476{
477 set_dirty();
478
479 const int list_index = get_children(name);
481 child_list& list = children_[list_index].second;
482 if(list.size() > std::numeric_limits<unsigned short>::max()) {
483 throw error("too many child elements");
484 }
485 list.push_back(new node(*doc_, this));
486 ordered_children_.emplace_back(list_index, list.size() - 1);
488 return *list.back();
489}
490
491void node::remove_child(const string_span& name, std::size_t index)
492{
493 set_dirty();
494
495 //if we don't already have a vector for this item we don't want to add one.
496 child_map::iterator itor = find_in_map(children_, name);
497 if(itor == children_.end()) {
498 return;
499 }
500
501 child_list& list = itor->second;
502 if(index >= list.size()) {
503 return;
504 }
505
506 remove_ordered_child(std::distance(children_.begin(), itor), index);
507
508 debug_delete(list[index]);
509 list.erase(list.begin() + index);
510
511 if(list.empty()) {
512 remove_ordered_child_list(std::distance(children_.begin(), itor));
513 children_.erase(itor);
514 }
515}
516
517void node::insert_ordered_child(int child_map_index, int child_list_index)
518{
519 bool inserted = false;
520 std::vector<node_pos>::iterator i = ordered_children_.begin();
521 while(i != ordered_children_.end()) {
522 if(i->child_map_index == child_map_index && i->child_list_index > child_list_index) {
523 i->child_list_index++;
524 } else if(i->child_map_index == child_map_index && i->child_list_index == child_list_index) {
525 inserted = true;
526 i->child_list_index++;
527 i = ordered_children_.insert(i, node_pos(child_map_index, child_list_index));
528 ++i;
529 }
530
531 ++i;
532 }
533
534 if(!inserted) {
535 ordered_children_.emplace_back(child_map_index, child_list_index);
536 }
537}
538
539void node::remove_ordered_child(int child_map_index, int child_list_index)
540{
541 int erase_count = 0;
542 std::vector<node_pos>::iterator i = ordered_children_.begin();
543 while(i != ordered_children_.end()) {
544 if(i->child_map_index == child_map_index && i->child_list_index == child_list_index) {
545 i = ordered_children_.erase(i);
546 ++erase_count;
547 } else {
548 if(i->child_map_index == child_map_index && i->child_list_index > child_list_index) {
549 i->child_list_index--;
550 }
551 ++i;
552 }
553 }
554
555 assert(erase_count == 1);
556}
557
558void node::remove_ordered_child_list(int child_map_index)
559{
560 std::vector<node_pos>::iterator i = ordered_children_.begin();
561 while(i != ordered_children_.end()) {
562 if(i->child_map_index == child_map_index) {
563 assert(false);
564 i = ordered_children_.erase(i);
565 } else {
566 if(i->child_map_index > child_map_index) {
567 i->child_map_index--;
568 }
569
570 ++i;
571 }
572 }
573}
574
576{
577// only define this symbol in debug mode to work out child ordering.
578#ifdef CHECK_ORDERED_CHILDREN
579 std::vector<node_pos>::const_iterator i = ordered_children_.begin();
580 while(i != ordered_children_.end()) {
581 assert(i->child_map_index < children_.size());
582 assert(i->child_list_index < children_[i->child_map_index].second.size());
583 ++i;
584 }
585
586 for(child_map::const_iterator j = children_.begin(); j != children_.end(); ++j) {
587 const unsigned short child_map_index = j - children_.begin();
588 for(child_list::const_iterator k = j->second.begin(); k != j->second.end(); ++k) {
589 const unsigned short child_list_index = k - j->second.begin();
590 bool found = false;
591 for(int n = 0; n != ordered_children_.size(); ++n) {
592 if(ordered_children_[n].child_map_index == child_map_index &&
593 ordered_children_[n].child_list_index == child_list_index) {
594 found = true;
595 break;
596 }
597 }
598
599 assert(found);
600 }
601 }
602#endif // CHECK_ORDERED_CHILDREN
603}
604
605void node::remove_child(const char* name, std::size_t index)
606{
607 remove_child(string_span(name), index);
608}
609
610node* node::child(const char* name)
611{
612 for(auto& [key, node_list] : children_) {
613 if(key == name) {
614 assert(node_list.empty() == false);
615 return node_list.front();
616 }
617 }
618
619 return nullptr;
620}
621
622const node* node::child(const char* name) const
623{
624 for(const auto& [key, node_list] : children_) {
625 if(key == name) {
626 if(node_list.empty()) {
627 return nullptr;
628 } else {
629 return node_list.front();
630 }
631 }
632 }
633
634 return nullptr;
635}
636
637node& node::child_or_add(const char* name)
638{
639 if(node* res = child(name)) {
640 return *res;
641 }
642 return add_child(name);
643}
644
645const node::child_list& node::children(const char* name) const
646{
647 for(const auto& [key, node_list] : children_) {
648 if(key == name) {
649 return node_list;
650 }
651 }
652
653 static const node::child_list empty;
654 return empty;
655}
656
657int node::get_children(const char* name)
658{
659 return get_children(string_span(name));
660}
661
663{
664 for(child_map::iterator i = children_.begin(); i != children_.end(); ++i) {
665 if(i->first == name) {
666 return std::distance(children_.begin(), i);
667 }
668 }
669
670 if(children_.size() > std::numeric_limits<unsigned short>::max()) {
671 throw error("too many child elements");
672 }
673 children_.emplace_back(string_span(name), child_list());
674 return children_.size() - 1;
675}
676
677node::child_map::const_iterator node::find_in_map(const child_map& m, const string_span& attr)
678{
679 child_map::const_iterator i = m.begin();
680 for(; i != m.end(); ++i) {
681 if(i->first == attr) {
682 break;
683 }
684 }
685
686 return i;
687}
688
689node::child_map::iterator node::find_in_map(child_map& m, const string_span& attr)
690{
691 child_map::iterator i = m.begin();
692 for(; i != m.end(); ++i) {
693 if(i->first == attr) {
694 break;
695 }
696 }
697
698 return i;
699}
700
702{
703 if(children_.empty()) {
704 static const string_span empty;
705 return empty;
706 }
707
708 return children_.begin()->first;
709}
710
712{
714 if(output_cache_.empty() == false) {
715 return output_cache_.size();
716 }
717
718 int res = 0;
719 for(const auto& [key, value] : attr_) {
720 res += key.size() + value.size() + 4;
721 }
722
723 std::size_t count_children = 0;
724 for(const auto& [key, node_list] : children_) {
725 for(const simple_wml::node* child_node : node_list) {
726 res += key.size() * 2 + 7;
727 res += child_node->output_size();
728 ++count_children;
729 }
730 }
731
732 assert(count_children == ordered_children_.size());
733
734 return res;
735}
736
737void node::shift_buffers(ptrdiff_t offset)
738{
739 if(!output_cache_.empty()) {
741 }
742
743 for(auto& [key, value] : attr_) {
744 key = string_span(key.begin() + offset, key.size());
745 value = string_span(value.begin() + offset, value.size());
746 }
747
748 for(auto& [key, node_list] : children_) {
749 key = string_span(key.begin() + offset, key.size());
750 for(simple_wml::node* child_node : node_list) {
751 child_node->shift_buffers(offset);
752 }
753 }
754}
755
756void node::output(char*& buf, CACHE_STATUS cache_status)
757{
758 if(output_cache_.empty() == false) {
759 memcpy(buf, output_cache_.begin(), output_cache_.size());
760 if(cache_status == REFRESH_CACHE) {
762 }
763 buf += output_cache_.size();
764 return;
765 }
766
767 char* begin = buf;
768
769 for(auto& [key, value] : attr_) {
770 memcpy(buf, key.begin(), key.size());
771 if(cache_status == REFRESH_CACHE) {
772 key = string_span(buf, key.size());
773 }
774 buf += key.size();
775 *buf++ = '=';
776 *buf++ = '"';
777 memcpy(buf, value.begin(), value.size());
778 if(cache_status == REFRESH_CACHE) {
779 value = string_span(buf, value.size());
780 }
781 buf += value.size();
782 *buf++ = '"';
783 *buf++ = '\n';
784 }
785
786 for(const node::node_pos& pos : ordered_children_) {
787 assert(pos.child_map_index < children_.size());
788 assert(pos.child_list_index < children_[pos.child_map_index].second.size());
789 string_span& attr = children_[pos.child_map_index].first;
790 *buf++ = '[';
791 memcpy(buf, attr.begin(), attr.size());
792 if(cache_status == REFRESH_CACHE) {
793 attr = string_span(buf, attr.size());
794 }
795 buf += attr.size();
796 *buf++ = ']';
797 *buf++ = '\n';
798 children_[pos.child_map_index].second[pos.child_list_index]->output(buf, cache_status);
799 *buf++ = '[';
800 *buf++ = '/';
801 memcpy(buf, attr.begin(), attr.size());
802 buf += attr.size();
803 *buf++ = ']';
804 *buf++ = '\n';
805 }
806
807 if(cache_status == REFRESH_CACHE) {
808 output_cache_ = string_span(begin, buf - begin);
809 }
810}
811
812std::string node_to_string(const node& n)
813{
814 //calling output with status=DO_NOT_MODIFY_CACHE really doesn't modify the
815 //node, so we can do it safely
816 node& mutable_node = const_cast<node&>(n);
817 std::vector<char> v(mutable_node.output_size());
818 char* ptr = &v[0];
819 mutable_node.output(ptr, node::DO_NOT_MODIFY_CACHE);
820 assert(ptr == &v[0] + v.size());
821 return std::string(v.begin(), v.end());
822}
823
825{
826 n.set_dirty();
827 for(const node::attribute& a : attr_) {
828 char* key = a.key.duplicate();
829 char* value = a.value.duplicate();
830 n.doc_->take_ownership_of_buffer(key);
831 n.doc_->take_ownership_of_buffer(value);
832 n.set_attr(key, value);
833 }
834
835 for(const node::node_pos& pos : ordered_children_) {
836 assert(pos.child_map_index < children_.size());
837 assert(pos.child_list_index < children_[pos.child_map_index].second.size());
838 char* buf = children_[pos.child_map_index].first.duplicate();
839 n.doc_->take_ownership_of_buffer(buf);
840 children_[pos.child_map_index].second[pos.child_list_index]->copy_into(n.add_child(buf));
841 }
842}
843
844void node::apply_diff(const node& diff)
845{
846 set_dirty();
847 const node* inserts = diff.child("insert");
848 if(inserts != nullptr) {
849 for(const node::attribute& a : inserts->attr_) {
850 char* name = a.key.duplicate();
851 char* value = a.value.duplicate();
852 set_attr(name, value);
855 }
856 }
857
858 const node* deletes = diff.child("delete");
859 if(deletes != nullptr) {
860 for(const node::attribute& a : deletes->attr_) {
861 std::pair<attribute_list::iterator,
862 attribute_list::iterator> range = std::equal_range(attr_.begin(), attr_.end(), a.key, string_span_pair_comparer());
863 if(range.first != range.second) {
864 attr_.erase(range.first);
865 }
866 }
867 }
868
869 for(const simple_wml::node* node : diff.children("change_child")) {
870 const std::size_t index = (*node)["index"].to_int();
871 for(const auto& [name, node_list] : node->children_) {
872 for(const simple_wml::node* child_node : node_list) {
873 child_map::iterator itor = find_in_map(children_, name);
874 if(itor != children_.end()) {
875 if(index < itor->second.size()) {
876 itor->second[index]->apply_diff(*child_node);
877 }
878 }
879 }
880 }
881 }
882
883 for(const simple_wml::node* node : diff.children("insert_child")) {
884 const std::size_t index = (*node)["index"].to_int();
885 for(const auto& [name, node_list] : node->children_) {
886 for(const simple_wml::node* child_node : node_list) {
887 char* buf = name.duplicate();
889 child_node->copy_into(add_child_at(buf, index));
890 }
891 }
892 }
893
894 for(const simple_wml::node* node : diff.children("delete_child")) {
895 const std::size_t index = (*node)["index"].to_int();
896 for(const auto& [name, node_list] : node->children_) {
897 if(node_list.empty()) {
898 continue;
899 }
900
901 remove_child(name, index);
902 }
903 }
904}
905
907{
908 doc_ = doc;
909
910 for(const auto& [_, node_list] : children_) {
911 for(simple_wml::node* child_node : node_list) {
912 child_node->set_doc(doc);
913 }
914 }
915}
916
918{
919 int res = 0;
920 for(const auto& [_, node_list] : children_) {
921 for(const simple_wml::node* child_node : node_list) {
922 ++res;
923 res += child_node->nchildren();
924 }
925 }
926
927 return res;
928}
929
931{
932 int res = attr_.capacity();
933 for(const auto& [_, node_list] : children_) {
934 for(const simple_wml::node* child_node : node_list) {
935 res += child_node->nattributes_recursive();
936 }
937 }
938
939 return res;
940}
941
943{
944 for(node* n = this; n != nullptr && n->output_cache_.is_null() == false; n = n->parent_) {
945 n->output_cache_ = string_span();
946 }
947}
948
950 compressed_buf_(),
951 output_(nullptr),
952 buffers_(),
953 root_(new node(*this, nullptr)),
954 prev_(nullptr),
955 next_(nullptr)
956{
957 attach_list();
958}
959
961 compressed_buf_(),
962 output_(buf),
963 buffers_(),
964 root_(nullptr),
965 prev_(nullptr),
966 next_(nullptr)
967{
968 if(control == INIT_TAKE_OWNERSHIP) {
969 buffers_.push_back(buf);
970 }
971 const char* cbuf = buf;
972 root_ = new node(*this, nullptr, &cbuf);
973
974 attach_list();
975}
976
977document::document(const char* buf, INIT_STATE state) :
978 compressed_buf_(),
979 output_(buf),
980 buffers_(),
981 root_(nullptr),
982 prev_(nullptr),
983 next_(nullptr)
984{
985 if(state == INIT_COMPRESSED) {
987 output_ = nullptr;
988 } else {
989 root_ = new node(*this, nullptr, &buf);
990 }
991
992 attach_list();
993}
994
996 compressed_buf_(compressed_buf),
997 output_(nullptr),
998 buffers_(),
999 root_(nullptr),
1000 prev_(nullptr),
1001 next_(nullptr)
1002{
1003 string_span uncompressed_buf;
1004 buffers_.push_back(uncompress_buffer(compressed_buf, &uncompressed_buf));
1005 output_ = uncompressed_buf.begin();
1006 const char* cbuf = output_;
1007 try {
1008 root_ = new node(*this, nullptr, &cbuf);
1009 } catch(...) {
1010 ERR_SWML << "Caught exception creating a new simple_wml node: " << utils::get_unknown_exception_type();
1011 delete [] buffers_.front();
1012 buffers_.clear();
1013 throw;
1014 }
1015
1016 attach_list();
1017}
1018
1020{
1021 for(std::vector<char*>::iterator i = buffers_.begin(); i != buffers_.end(); ++i) {
1022 delete [] *i;
1023 }
1024
1025 buffers_.clear();
1026 debug_delete(root_);
1027
1028 detach_list();
1029}
1030
1031const char* document::dup_string(const char* str)
1032{
1033 return dup_string(string_span(str));
1034}
1035
1037{
1038 char* res = new char[str.size() + 1];
1039 std::memcpy(res, str.begin(), str.size());
1040 res[str.size()] = '\0';
1041 buffers_.push_back(res);
1042 return res;
1043}
1044
1046{
1047 const std::string escaped = utils::wml_escape_string(str);
1048 return dup_string(string_span(escaped));
1049}
1050
1051const char* document::output()
1052{
1053 if(output_ && (!root_ || root_->is_dirty() == false)) {
1054 return output_;
1055 }
1056 if(!root_) {
1057 assert(compressed_buf_.empty() == false);
1058 string_span uncompressed_buf;
1059 buffers_.push_back(uncompress_buffer(compressed_buf_, &uncompressed_buf));
1060 output_ = uncompressed_buf.begin();
1061 return output_;
1062 }
1063
1064 //we're dirty, so the compressed buf must also be dirty; clear it.
1066
1067 std::vector<char*> bufs;
1068 bufs.swap(buffers_);
1069
1070 const int buf_size = root_->output_size() + 1;
1071 char* buf;
1072 try {
1073 buf = new char[buf_size];
1074 } catch (const std::bad_alloc& e) {
1075 ERR_SWML << "ERROR: Trying to allocate " << buf_size << " bytes. "
1076 << e.what();
1077 throw error("Bad allocation request in output().");
1078 }
1079 buffers_.push_back(buf);
1080 output_ = buf;
1081
1083 *buf++ = 0;
1084 assert(buf == output_ + buf_size);
1085
1086 for(std::vector<char*>::iterator i = bufs.begin(); i != bufs.end(); ++i) {
1087 delete [] *i;
1088 }
1089
1090 bufs.clear();
1091
1092 return output_;
1093}
1094
1096{
1097 if(compressed_buf_.empty() == false &&
1098 (root_ == nullptr || root_->is_dirty() == false)) {
1099 assert(*compressed_buf_.begin() == (bzip2 ? 'B' : 31));
1100 return compressed_buf_;
1101 }
1102
1103 buffers_.push_back(compress_buffer(output(), &compressed_buf_, bzip2));
1104 assert(*compressed_buf_.begin() == (bzip2 ? 'B' : 31));
1105
1106 return compressed_buf_;
1107}
1108
1110{
1112 debug_delete(root_);
1113 root_ = nullptr;
1114 output_ = nullptr;
1115 std::vector<char*> new_buffers;
1116 for(std::vector<char*>::iterator i = buffers_.begin(); i != buffers_.end(); ++i) {
1117 if(*i != compressed_buf_.begin()) {
1118 delete [] *i;
1119 } else {
1120 new_buffers.push_back(*i);
1121 }
1122 }
1123
1124 buffers_.swap(new_buffers);
1125 assert(buffers_.size() == 1);
1126}
1127
1129{
1130 if(output_ == nullptr) {
1131 assert(compressed_buf_.empty() == false);
1132 string_span uncompressed_buf;
1133 buffers_.push_back(uncompress_buffer(compressed_buf_, &uncompressed_buf));
1134 output_ = uncompressed_buf.begin();
1135 }
1136
1137 assert(root_ == nullptr);
1138 const char* cbuf = output_;
1139 root_ = new node(*this, nullptr, &cbuf);
1140}
1141
1142std::unique_ptr<document> document::clone()
1143{
1144 char* buf = new char[strlen(output())+1];
1145 strcpy(buf, output());
1146 return std::make_unique<document>(buf);
1147}
1148
1149void document::swap(document& o) noexcept
1150{
1151 std::swap(compressed_buf_, o.compressed_buf_);
1152 std::swap(output_, o.output_);
1153 buffers_.swap(o.buffers_);
1154 std::swap(root_, o.root_);
1155
1156 root_->set_doc(this);
1157 o.root_->set_doc(&o);
1158}
1159
1161{
1163 output_ = nullptr;
1164 debug_delete(root_);
1165 root_ = new node(*this, nullptr);
1166 for(std::vector<char*>::iterator i = buffers_.begin(); i != buffers_.end(); ++i) {
1167 delete [] *i;
1168 }
1169
1170 buffers_.clear();
1171}
1172
1173namespace {
1174document* head_doc = nullptr;
1175}
1176
1178{
1179 prev_ = nullptr;
1180 next_ = head_doc;
1181
1182 if(next_) {
1183 next_->prev_ = this;
1184 }
1185 head_doc = this;
1186}
1187
1189{
1190 if(head_doc == this) {
1191 head_doc = next_;
1192 }
1193
1194 if(next_) {
1195 next_->prev_ = prev_;
1196 }
1197
1198 if(prev_) {
1199 prev_->next_ = next_;
1200 }
1201 next_ = prev_ = nullptr;
1202}
1203
1204std::string document::stats()
1205{
1206 std::ostringstream s;
1207 int ndocs = 0;
1208 int ncompressed = 0;
1209 int compressed_size = 0;
1210 int ntext = 0;
1211 int text_size = 0;
1212 int nbuffers = 0;
1213 int nnodes = 0;
1214 int ndirty = 0;
1215 int nattributes = 0;
1216 for(document* d = head_doc; d != nullptr; d = d->next_) {
1217 ndocs++;
1218 nbuffers += d->buffers_.size();
1219
1220 if(d->compressed_buf_.is_null() == false) {
1221 ++ncompressed;
1222 compressed_size += d->compressed_buf_.size();
1223 }
1224
1225 if(d->output_) {
1226 ++ntext;
1227 text_size += strlen(d->output_);
1228 }
1229
1230 if(d->root_) {
1231 nnodes += 1 + d->root_->nchildren();
1232 nattributes += d->root_->nattributes_recursive();
1233 }
1234
1235 if(d->root_ && d->root_->is_dirty()) {
1236 ++ndirty;
1237 }
1238 }
1239
1240 const int nodes_alloc = nnodes*(sizeof(node) + 12);
1241 const int attr_alloc = nattributes*(sizeof(string_span)*2);
1242 const int total_alloc = compressed_size + text_size + nodes_alloc + attr_alloc;
1243
1244 s << "WML documents: " << ndocs << "\n"
1245 << "Dirty: " << ndirty << "\n"
1246 << "With compression: " << ncompressed << " (" << compressed_size
1247 << " bytes)\n"
1248 << "With text: " << ntext << " (" << text_size
1249 << " bytes)\n"
1250 << "Nodes: " << nnodes << " (" << nodes_alloc << " bytes)\n"
1251 << "Attr: " << nattributes << " (" << attr_alloc << " bytes)\n"
1252 << "Buffers: " << nbuffers << "\n"
1253 << "Total allocation: " << total_alloc << " bytes\n";
1254
1255 return s.str();
1256}
1257
1258void swap(document& lhs, document& rhs) noexcept
1259{
1260 lhs.swap(rhs);
1261}
1262
1263}
unsigned in
If equal to search_counter, the node is off the list.
void take_ownership_of_buffer(char *buffer)
const char * output()
std::unique_ptr< document > clone()
static std::string stats()
static std::size_t document_size_limit
void swap(document &o) noexcept
const char * esc_string(string_span str)
std::vector< char * > buffers_
string_span output_compressed(bool bzip2=false)
const char * dup_string(const char *str)
string_span compressed_buf_
const string_span & attr(const char *key) const
int output_size() const
void set_doc(document *doc)
void insert_ordered_child(int child_map_index, int child_list_index)
void check_ordered_children() const
void remove_child(const char *name, std::size_t index)
int nchildren() const
bool is_dirty() const
node(document &doc, node *parent)
int get_children(const string_span &name)
const string_span & operator[](const char *key) const
const child_list & children(const char *name) const
void apply_diff(const node &diff)
attribute_list attr_
bool has_attr(const char *key) const
node & set_attr_int(const char *key, int value)
std::vector< child_pair > child_map
node * child(const char *name)
std::vector< node * > child_list
void remove_ordered_child_list(int child_map_index)
int nattributes_recursive() const
std::vector< node_pos > ordered_children_
const string_span & first_child() const
child_map children_
void output(char *&buf, CACHE_STATUS status=DO_NOT_MODIFY_CACHE)
node & add_child(const char *name)
node & child_or_add(const char *name)
node & set_attr_esc(const char *key, string_span value)
As above but convert value to a WML value
node & set_attr(const char *key, const char *value)
string_span output_cache_
node & add_child_at(const char *name, std::size_t index)
void copy_into(node &n) const
node & set_attr_dup(const char *key, const char *value)
void remove_ordered_child(int child_map_index, int child_list_index)
void shift_buffers(ptrdiff_t offset)
static child_map::const_iterator find_in_map(const child_map &m, const string_span &attr)
bool to_bool(bool default_value=false) const
std::string to_string() const
char * duplicate() const
const char * end() const
const char * begin() const
static std::string _(const char *str)
Definition gettext.hpp:100
Standard logging facilities (interface).
void swap(document &lhs, document &rhs) noexcept
Implement non-member swap function for std::swap (calls document::swap).
std::ostream & operator<<(std::ostream &o, const string_span &s)
std::string node_to_string(const node &n)
std::string get_unknown_exception_type()
Utility function for finding the type of thing caught with catch(...).
Definition general.cpp:23
std::string wml_escape_string(std::string_view str)
Format str as a WML value
#define ERR_SWML
static lg::log_domain log_config("config")
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
Definition sound.cpp:139
static map_location::direction n
static map_location::direction s
#define i
#define d
#define e
#define b