Use StringRef through XmlEncode

This introduces a potential lifetime risk when using the API, but
the intended way to use the `XmlEncode` class is to use it directly,
e.g. `out << XmlEncode(some-text-argument)`, not to store it around.

The benefit is that we avoid allocations for strings that do not fit
into SSO for given platform.
This commit is contained in:
Martin Hořeňovský 2021-05-29 16:37:51 +02:00
parent aba114d6fe
commit 1d04427fcd
No known key found for this signature in database
GPG Key ID: DE48307B8B0D381A
2 changed files with 10 additions and 3 deletions

View File

@ -77,7 +77,7 @@ namespace {
} }
XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) XmlEncode::XmlEncode( StringRef str, ForWhat forWhat )
: m_str( str ), : m_str( str ),
m_forWhat( forWhat ) m_forWhat( forWhat )
{} {}

View File

@ -9,6 +9,7 @@
#define CATCH_XMLWRITER_HPP_INCLUDED #define CATCH_XMLWRITER_HPP_INCLUDED
#include <catch2/internal/catch_stream.hpp> #include <catch2/internal/catch_stream.hpp>
#include <catch2/internal/catch_stringref.hpp>
#include <vector> #include <vector>
@ -22,18 +23,24 @@ namespace Catch {
XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs); XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs); XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
/**
* Helper for XML-encoding text (escaping angle brackets, quotes, etc)
*
* Note: doesn't take ownership of passed strings, and thus the
* encoded string must outlive the encoding instance.
*/
class XmlEncode { class XmlEncode {
public: public:
enum ForWhat { ForTextNodes, ForAttributes }; enum ForWhat { ForTextNodes, ForAttributes };
XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); XmlEncode( StringRef str, ForWhat forWhat = ForTextNodes );
void encodeTo( std::ostream& os ) const; void encodeTo( std::ostream& os ) const;
friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
private: private:
std::string m_str; StringRef m_str;
ForWhat m_forWhat; ForWhat m_forWhat;
}; };