diff --git a/include/cereal/archives/xml.hpp b/include/cereal/archives/xml.hpp index 575c11c9c..d04cf6afa 100644 --- a/include/cereal/archives/xml.hpp +++ b/include/cereal/archives/xml.hpp @@ -233,9 +233,12 @@ namespace cereal itsOS << value << std::ends; const auto strValue = itsOS.str(); - // if there is the first or the last character in string is whitespace then add xml:space attribute - // the last character has index length-2 because there is \0 character at end added with std::ends - if( !strValue.empty() && ( xml_detail::isWhitespace( strValue[0] ) || xml_detail::isWhitespace( strValue[strValue.length() - 2] ) ) ) + + // If the first or last character is a whitespace, add xml:space attribute + // the string always contains a '\0' added by std::ends, so the last character is at len-2 and an 'empty' + // string has a length of 1 or lower + const auto len = strValue.length(); + if ( len > 1 && ( xml_detail::isWhitespace( strValue[0] ) || xml_detail::isWhitespace( strValue[len - 2] ) ) ) { itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "xml:space", "preserve" ) ); } diff --git a/unittests/basic_string.cpp b/unittests/basic_string.cpp index ea523e50a..ede18525c 100644 --- a/unittests/basic_string.cpp +++ b/unittests/basic_string.cpp @@ -38,16 +38,19 @@ void test_string_basic() { std::basic_string o_string = random_basic_string(gen); std::basic_string o_string2 = ""; + std::basic_string o_string3; std::ostringstream os; { OArchive oar(os); oar(o_string); oar(o_string2); + oar(o_string3); } std::basic_string i_string; std::basic_string i_string2; + std::basic_string i_string3; std::istringstream is(os.str()); { @@ -55,10 +58,12 @@ void test_string_basic() iar(i_string); iar(i_string2); + iar(i_string3); } BOOST_CHECK_EQUAL(i_string, o_string); BOOST_CHECK_EQUAL(i_string2, o_string2); + BOOST_CHECK_EQUAL(i_string3, o_string3); } } @@ -148,7 +153,6 @@ void test_ws_in_out(Out const & o_value_with_ws) namespace boost { - void save( cereal::XMLOutputArchive & ar, boost::string_ref const & str ) { ar.saveValue( str );