Skip to content

Commit

Permalink
Merge pull request #664 from zeux/emptybuf
Browse files Browse the repository at this point in the history
Early out in load_buffer for empty inputs to avoid allocations
  • Loading branch information
zeux authored Feb 19, 2025
2 parents a340834 + 709ba74 commit 066b658
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/pugixml.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ PUGI_IMPL_NS_BEGIN

while (srclen && *dst && *src == *dst)
{
--srclen; ++dst; ++src;
--srclen; ++dst; ++src;
}
return srclen == 0 && *dst == 0;
}
Expand Down Expand Up @@ -4780,6 +4780,9 @@ PUGI_IMPL_NS_BEGIN
// if convert_buffer below throws bad_alloc, we still need to deallocate contents if we own it
auto_deleter<void> contents_guard(own ? contents : NULL, xml_memory::deallocate);

// early-out for empty documents to avoid buffer allocation overhead
if (size == 0) return make_parse_result((options & parse_fragment) ? status_ok : status_no_document_element);

// get private buffer
char_t* buffer = NULL;
size_t length = 0;
Expand Down
24 changes: 24 additions & 0 deletions tests/test_document.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,17 @@ TEST(document_load_string)
CHECK_NODE(doc, STR("<node/>"));
}

TEST(document_load_string_empty)
{
xml_document doc;

CHECK(doc.load_string(STR("")).status == status_no_document_element);
CHECK(!doc.first_child());

CHECK(doc.load_string(STR(""), parse_fragment));
CHECK(!doc.first_child());
}

TEST(document_load_file)
{
xml_document doc;
Expand Down Expand Up @@ -864,6 +875,19 @@ TEST(document_load_buffer_inplace_own)
CHECK_NODE(doc, STR("<node/>"));
}

TEST(document_load_buffer_inplace_own_empty)
{
allocation_function alloc = get_memory_allocation_function();

void* text1 = alloc(1);
void* text2 = alloc(1);
CHECK(text1 && text2);

xml_document doc;
CHECK(doc.load_buffer_inplace_own(text1, 0, parse_fragment));
CHECK(doc.load_buffer_inplace_own(text2, 0).status == status_no_document_element);
}

TEST(document_parse_result_bool)
{
xml_parse_result result;
Expand Down

0 comments on commit 066b658

Please sign in to comment.