Tweaked rawMemoryToString() along lines of suggestion in #281

This commit is contained in:
Phil Nash 2014-05-23 18:41:02 +01:00
parent 48fac9cf01
commit 7cbf74061b
3 changed files with 46 additions and 33 deletions

View File

@ -80,41 +80,11 @@ namespace Detail {
} }
}; };
struct Endianness { std::string rawMemoryToString( const void *object, std::size_t size );
enum Arch { Big, Little };
static Arch which() {
union _{
int asInt;
char asChar[sizeof (int)];
} u;
u.asInt = 1;
return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
}
};
// Writes the raw memory into a string, considering endianness
template<typename T> template<typename T>
std::string rawMemoryToString( T value ) { inline std::string rawMemoryToString( const T& object ) {
union _ { return rawMemoryToString( &object, sizeof(object) );
T typedValue;
unsigned char bytes[sizeof(T)];
} u;
u.typedValue = value;
std::ostringstream oss;
oss << "0x";
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)u.bytes[i];
return oss.str();
} }
} // end namespace Detail } // end namespace Detail

View File

@ -13,6 +13,42 @@
namespace Catch { namespace Catch {
namespace Detail {
namespace {
struct Endianness {
enum Arch { Big, Little };
static Arch which() {
union _{
int asInt;
char asChar[sizeof (int)];
} u;
u.asInt = 1;
return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
}
};
}
std::string rawMemoryToString( const void *object, std::size_t size )
{
// Reverse order for little endian architectures
int i = 0, end = static_cast<int>( size ), inc = 1;
if( Endianness::which() == Endianness::Little ) {
i = end-1;
end = inc = -1;
}
unsigned char const *bytes = static_cast<unsigned char const *>(object);
std::ostringstream os;
os << "0x" << std::setfill('0') << std::hex;
for( ; i != end; i += inc )
os << std::setw(2) << static_cast<unsigned>(bytes[i]);
return os.str();
}
}
std::string toString( std::string const& value ) { std::string toString( std::string const& value ) {
std::string s = value; std::string s = value;
if( getCurrentContext().getConfig()->showInvisibles() ) { if( getCurrentContext().getConfig()->showInvisibles() ) {

View File

@ -123,3 +123,10 @@ TEST_CASE( "sends information to INFO", "[.][failing]" )
CAPTURE( i ); CAPTURE( i );
REQUIRE( false ); REQUIRE( false );
} }
TEST_CASE( "Pointers can be converted to strings", "[messages][.]" )
{
int p;
WARN( "actual address of p: " << &p );
WARN( "toString(p): " << Catch::toString( &p ) );
}