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

Optimize writing of non-string values to JSON

In practice, the majority of values the JSON writer handles are
strings, but this makes the code more obvious and can still provide
a small speed-up.
Commit
46bdf1a04c92e7d34ee24f95d8d8a862498eede7
Author
Martin Hořeňovský ·
Parents
c267251e709c

Files · Download .tar.gz

Changes

 src/catch2/internal/catch_jsonwriter.cpp | 33 ++++++++++++++++++++------------
 1 file changed, 21 insertions(+), 12 deletions(-)

diff --git a/src/catch2/internal/catch_jsonwriter.cpp b/src/catch2/internal/catch_jsonwriter.cpp
index d5122dbc..a33590f0 100644
--- a/src/catch2/internal/catch_jsonwriter.cpp
+++ b/src/catch2/internal/catch_jsonwriter.cpp
@@ -172,21 +172,30 @@ namespace Catch {
     }
 
     void JsonValueWriter::writeImpl( Catch::StringRef value, bool quote ) {
-        if ( quote ) { m_os << '"'; }
-        size_t current_start = 0;
-        for ( size_t i = 0; i < value.size(); ++i ) {
-            if ( needsEscape( value[i] ) ) {
-                if ( current_start < i ) {
-                    m_os << value.substr( current_start, i - current_start );
+        // Escaping only makes sense for actual strings, which are passed
+        // with `quote == true`. Non-quoted values are things like bools
+        // and numbers, which cannot create inputs that need escaping.
+        if ( !quote ) {
+            m_os << value;
+        } else {
+            m_os << '"';
+            size_t current_start = 0;
+            for ( size_t i = 0; i < value.size(); ++i ) {
+                if ( needsEscape( value[i] ) ) {
+                    if ( current_start < i ) {
+                        m_os
+                            << value.substr( current_start, i - current_start );
+                    }
+                    m_os << makeEscapeStringRef( value[i] );
+                    current_start = i + 1;
                 }
-                m_os << makeEscapeStringRef( value[i] );
-                current_start = i + 1;
             }
+            if ( current_start < value.size() ) {
+                m_os << value.substr( current_start,
+                                      value.size() - current_start );
+            }
+            m_os << '"';
         }
-        if ( current_start < value.size() ) {
-            m_os << value.substr( current_start, value.size() - current_start );
-        }
-        if ( quote ) { m_os << '"'; }
     }
 
 } // namespace Catch