Progmasoft Git

catch3

Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results.

Clonegit clone https://git.progmasoft.com/catch3

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.
Commit
1d04427fcdf81fb13c754c659f4bcde0403a8855
Author
Martin Hořeňovský ·
Parents
aba114d6fed8

Files · Download .tar.gz

Changes

 src/catch2/internal/catch_xmlwriter.cpp |  2 +-
 src/catch2/internal/catch_xmlwriter.hpp | 11 +++++++++--
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/src/catch2/internal/catch_xmlwriter.cpp b/src/catch2/internal/catch_xmlwriter.cpp
index f8e18240..63e6be1f 100644
--- a/src/catch2/internal/catch_xmlwriter.cpp
+++ b/src/catch2/internal/catch_xmlwriter.cpp
@@ -77,7 +77,7 @@ namespace {
     }
 
 
-    XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
+    XmlEncode::XmlEncode( StringRef str, ForWhat forWhat )
     :   m_str( str ),
         m_forWhat( forWhat )
     {}
diff --git a/src/catch2/internal/catch_xmlwriter.hpp b/src/catch2/internal/catch_xmlwriter.hpp
index e1e99659..19642db2 100644
--- a/src/catch2/internal/catch_xmlwriter.hpp
+++ b/src/catch2/internal/catch_xmlwriter.hpp
@@ -9,6 +9,7 @@
 #define CATCH_XMLWRITER_HPP_INCLUDED
 
 #include <catch2/internal/catch_stream.hpp>
+#include <catch2/internal/catch_stringref.hpp>
 
 #include <vector>
 
@@ -22,18 +23,24 @@ namespace Catch {
     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 {
     public:
         enum ForWhat { ForTextNodes, ForAttributes };
 
-        XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
+        XmlEncode( StringRef str, ForWhat forWhat = ForTextNodes );
 
         void encodeTo( std::ostream& os ) const;
 
         friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
 
     private:
-        std::string m_str;
+        StringRef m_str;
         ForWhat m_forWhat;
     };