Skip to content

Commit 066b658

Browse files
authored
Merge pull request #664 from zeux/emptybuf
Early out in load_buffer for empty inputs to avoid allocations
2 parents a340834 + 709ba74 commit 066b658

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/pugixml.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ PUGI_IMPL_NS_BEGIN
264264

265265
while (srclen && *dst && *src == *dst)
266266
{
267-
--srclen; ++dst; ++src;
267+
--srclen; ++dst; ++src;
268268
}
269269
return srclen == 0 && *dst == 0;
270270
}
@@ -4780,6 +4780,9 @@ PUGI_IMPL_NS_BEGIN
47804780
// if convert_buffer below throws bad_alloc, we still need to deallocate contents if we own it
47814781
auto_deleter<void> contents_guard(own ? contents : NULL, xml_memory::deallocate);
47824782

4783+
// early-out for empty documents to avoid buffer allocation overhead
4784+
if (size == 0) return make_parse_result((options & parse_fragment) ? status_ok : status_no_document_element);
4785+
47834786
// get private buffer
47844787
char_t* buffer = NULL;
47854788
size_t length = 0;

tests/test_document.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,17 @@ TEST(document_load_string)
473473
CHECK_NODE(doc, STR("<node/>"));
474474
}
475475

476+
TEST(document_load_string_empty)
477+
{
478+
xml_document doc;
479+
480+
CHECK(doc.load_string(STR("")).status == status_no_document_element);
481+
CHECK(!doc.first_child());
482+
483+
CHECK(doc.load_string(STR(""), parse_fragment));
484+
CHECK(!doc.first_child());
485+
}
486+
476487
TEST(document_load_file)
477488
{
478489
xml_document doc;
@@ -864,6 +875,19 @@ TEST(document_load_buffer_inplace_own)
864875
CHECK_NODE(doc, STR("<node/>"));
865876
}
866877

878+
TEST(document_load_buffer_inplace_own_empty)
879+
{
880+
allocation_function alloc = get_memory_allocation_function();
881+
882+
void* text1 = alloc(1);
883+
void* text2 = alloc(1);
884+
CHECK(text1 && text2);
885+
886+
xml_document doc;
887+
CHECK(doc.load_buffer_inplace_own(text1, 0, parse_fragment));
888+
CHECK(doc.load_buffer_inplace_own(text2, 0).status == status_no_document_element);
889+
}
890+
867891
TEST(document_parse_result_bool)
868892
{
869893
xml_parse_result result;

0 commit comments

Comments
 (0)