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

Considers endianness when printing raw memory into a string

Commit
48153e8e1007b661e41ac6eeb8a6e3d255eca63a
Author
Phil Nash ·
Parents
878c257de7cb

Files · Download .tar.gz

Changes

 include/internal/catch_tostring.hpp | 27 +++++++++++++++++++++++----
 projects/SelfTest/MiscTests.cpp     |  4 ++++
 2 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/include/internal/catch_tostring.hpp b/include/internal/catch_tostring.hpp
index c081e944..788850ff 100644
--- a/include/internal/catch_tostring.hpp
+++ b/include/internal/catch_tostring.hpp
@@ -79,8 +79,21 @@ namespace Detail {
         }
     };
 
-    // For display purposes only.
-    // Does not consider endian-ness
+    struct Endianness {
+        enum Arch { Big, Little };
+
+        static Arch which() {
+            union {
+                int asInt;
+                char asChar[sizeof (int)];
+            };
+
+            asInt = 1;
+            return ( asChar[sizeof(int)-1] == 1 ) ? Big : Little;
+        }
+    };
+
+    // Writes the raw memory into a string, considering endianness
     template<typename T>
     std::string rawMemoryToString( T value ) {
         union {
@@ -92,8 +105,14 @@ namespace Detail {
 
         std::ostringstream oss;
         oss << "0x";
-        for( unsigned char* cp = bytes; cp < bytes+sizeof(T); ++cp )
-            oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)*cp;
+
+        int i = 0, end = sizeof(T), inc = 1;
+        if( Endianness::which() == Endianness::Little ) {
+            i = end-1;
+            end = inc = -1;
+        }
+        for( ; i != end; i += inc )
+            oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)bytes[i];
         return oss.str();
     }
 
diff --git a/projects/SelfTest/MiscTests.cpp b/projects/SelfTest/MiscTests.cpp
index 7c028ffa..30d66c3e 100644
--- a/projects/SelfTest/MiscTests.cpp
+++ b/projects/SelfTest/MiscTests.cpp
@@ -339,3 +339,7 @@ TEST_CASE("not allowed", "[!throws]")
     // This test case should not be included if you run with -e on the command line
     SUCCEED();
 }
+
+//TEST_CASE( "Is big endian" ) {
+//    CHECK( Catch::Detail::Endianness::which() == Catch::Detail::Endianness::Little );
+//}