HART  0.2.0
High level Audio Regression and Testing
Loading...
Searching...
No Matches
hart_stringify.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint> // uintptr_t
4#include <iomanip>
5#include <ostream>
6#include <sstream>
7#include <string>
8#include <type_traits>
9#include <utility>
10
11namespace hart
12{
13
14/// @brief A helper to test whether an object can be printed via the "<<" operator
15/// @private
16template <typename Type>
17class IsStreamInsertable
18{
19private:
20 template <typename CandidateType>
21 static auto test (int) -> decltype (
22 std::declval<std::ostream&>() << std::declval<const CandidateType&>(),
23 std::true_type()
24 );
25
26 template <typename>
27 static std::false_type test (...);
28
29public:
30 static const bool value = decltype (test<Type> (42))::value;
31};
32
33/// @private
34template <typename Type>
35std::string pointerToString (const Type* value)
36{
37 if (value == nullptr)
38 return "nullptr";
39
40 std::ostringstream stream;
41 stream << "<pointer to 0x" << std::hex << reinterpret_cast<std::uintptr_t> (value) << '>';
42 return stream.str();
43}
44
45/// @private
46template <typename Type>
47std::string objectAddressToString (const Type& value)
48{
49 std::ostringstream stream;
50 stream << "<object at 0x" << std::hex << reinterpret_cast<std::uintptr_t> (&value) << '>';
51 return stream.str();
52}
53
54/// @private
55inline std::string toString (const std::string& value)
56{
57 return '"' + value + '"';
58}
59
60/// @private
61inline std::string toString (const char* value)
62{
63 if (value == nullptr)
64 return "nullptr";
65
66 return '"' + std::string (value) + '"';
67}
68
69/// @private
70inline std::string toString (bool value)
71{
72 return value == true ? "true" : "false";
73}
74
75/// @brief Creates a string representation of a raw pointer
76/// @private
77template <typename Type>
78std::string toString (Type* value)
79{
80 return pointerToString (value);
81}
82
83/// @brief Creates a string representation of an object that supports printing via the "<<" operator
84/// @private
85template <typename Type>
86typename std::enable_if<IsStreamInsertable<Type>::value, std::string>::type
87toString (const Type& value)
88{
89 std::ostringstream stream;
90 stream << value;
91 return stream.str();
92}
93
94/// @brief Creates a fallback string representation of an object that doesn't support printing via the "<<" operator
95/// @private
96template <typename Type>
97typename std::enable_if<! IsStreamInsertable<Type>::value, std::string>::type
98toString (const Type& value)
99{
100 return objectAddressToString (value);
101}
102
103} // namespace hart