catch_tostring.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /*
  2. * Created by Phil on 8/5/2012.
  3. * Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
  4. *
  5. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
  9. #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
  10. #include <vector>
  11. #include <cstddef>
  12. #include <type_traits>
  13. #include <string>
  14. #include "catch_compiler_capabilities.h"
  15. #include "catch_stream.h"
  16. #include "catch_interfaces_enum_values_registry.h"
  17. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  18. #include <string_view>
  19. #endif
  20. #ifdef __OBJC__
  21. #include "catch_objc_arc.hpp"
  22. #endif
  23. #ifdef _MSC_VER
  24. #pragma warning(push)
  25. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  26. #endif
  27. namespace Catch {
  28. namespace Detail {
  29. extern const std::string unprintableString;
  30. std::string rawMemoryToString( const void *object, std::size_t size );
  31. template<typename T>
  32. std::string rawMemoryToString( const T& object ) {
  33. return rawMemoryToString( &object, sizeof(object) );
  34. }
  35. template<typename T>
  36. class IsStreamInsertable {
  37. template<typename Stream, typename U>
  38. static auto test(int)
  39. -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
  40. template<typename, typename>
  41. static auto test(...)->std::false_type;
  42. public:
  43. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  44. };
  45. template<typename E>
  46. std::string convertUnknownEnumToString( E e );
  47. template<typename T>
  48. typename std::enable_if<
  49. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  50. std::string>::type convertUnstreamable( T const& ) {
  51. return Detail::unprintableString;
  52. }
  53. template<typename T>
  54. typename std::enable_if<
  55. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  56. std::string>::type convertUnstreamable(T const& ex) {
  57. return ex.what();
  58. }
  59. template<typename T>
  60. typename std::enable_if<
  61. std::is_enum<T>::value
  62. , std::string>::type convertUnstreamable( T const& value ) {
  63. return convertUnknownEnumToString( value );
  64. }
  65. #if defined(_MANAGED)
  66. //! Convert a CLR string to a utf8 std::string
  67. template<typename T>
  68. std::string clrReferenceToString( T^ ref ) {
  69. if (ref == nullptr)
  70. return std::string("null");
  71. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  72. cli::pin_ptr<System::Byte> p = &bytes[0];
  73. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  74. }
  75. #endif
  76. } // namespace Detail
  77. // If we decide for C++14, change these to enable_if_ts
  78. template <typename T, typename = void>
  79. struct StringMaker {
  80. template <typename Fake = T>
  81. static
  82. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  83. convert(const Fake& value) {
  84. ReusableStringStream rss;
  85. // NB: call using the function-like syntax to avoid ambiguity with
  86. // user-defined templated operator<< under clang.
  87. rss.operator<<(value);
  88. return rss.str();
  89. }
  90. template <typename Fake = T>
  91. static
  92. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  93. convert( const Fake& value ) {
  94. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  95. return Detail::convertUnstreamable(value);
  96. #else
  97. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  98. #endif
  99. }
  100. };
  101. namespace Detail {
  102. // This function dispatches all stringification requests inside of Catch.
  103. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  104. template <typename T>
  105. std::string stringify(const T& e) {
  106. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  107. }
  108. template<typename E>
  109. std::string convertUnknownEnumToString( E e ) {
  110. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  111. }
  112. #if defined(_MANAGED)
  113. template <typename T>
  114. std::string stringify( T^ e ) {
  115. return ::Catch::StringMaker<T^>::convert(e);
  116. }
  117. #endif
  118. } // namespace Detail
  119. // Some predefined specializations
  120. template<>
  121. struct StringMaker<std::string> {
  122. static std::string convert(const std::string& str);
  123. };
  124. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  125. template<>
  126. struct StringMaker<std::string_view> {
  127. static std::string convert(std::string_view str);
  128. };
  129. #endif
  130. template<>
  131. struct StringMaker<char const *> {
  132. static std::string convert(char const * str);
  133. };
  134. template<>
  135. struct StringMaker<char *> {
  136. static std::string convert(char * str);
  137. };
  138. #ifdef CATCH_CONFIG_WCHAR
  139. template<>
  140. struct StringMaker<std::wstring> {
  141. static std::string convert(const std::wstring& wstr);
  142. };
  143. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  144. template<>
  145. struct StringMaker<std::wstring_view> {
  146. static std::string convert(std::wstring_view str);
  147. };
  148. # endif
  149. template<>
  150. struct StringMaker<wchar_t const *> {
  151. static std::string convert(wchar_t const * str);
  152. };
  153. template<>
  154. struct StringMaker<wchar_t *> {
  155. static std::string convert(wchar_t * str);
  156. };
  157. #endif
  158. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  159. // while keeping string semantics?
  160. template<int SZ>
  161. struct StringMaker<char[SZ]> {
  162. static std::string convert(char const* str) {
  163. return ::Catch::Detail::stringify(std::string{ str });
  164. }
  165. };
  166. template<int SZ>
  167. struct StringMaker<signed char[SZ]> {
  168. static std::string convert(signed char const* str) {
  169. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  170. }
  171. };
  172. template<int SZ>
  173. struct StringMaker<unsigned char[SZ]> {
  174. static std::string convert(unsigned char const* str) {
  175. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  176. }
  177. };
  178. #if defined(CATCH_CONFIG_CPP17_BYTE)
  179. template<>
  180. struct StringMaker<std::byte> {
  181. static std::string convert(std::byte value);
  182. };
  183. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  184. template<>
  185. struct StringMaker<int> {
  186. static std::string convert(int value);
  187. };
  188. template<>
  189. struct StringMaker<long> {
  190. static std::string convert(long value);
  191. };
  192. template<>
  193. struct StringMaker<long long> {
  194. static std::string convert(long long value);
  195. };
  196. template<>
  197. struct StringMaker<unsigned int> {
  198. static std::string convert(unsigned int value);
  199. };
  200. template<>
  201. struct StringMaker<unsigned long> {
  202. static std::string convert(unsigned long value);
  203. };
  204. template<>
  205. struct StringMaker<unsigned long long> {
  206. static std::string convert(unsigned long long value);
  207. };
  208. template<>
  209. struct StringMaker<bool> {
  210. static std::string convert(bool b);
  211. };
  212. template<>
  213. struct StringMaker<char> {
  214. static std::string convert(char c);
  215. };
  216. template<>
  217. struct StringMaker<signed char> {
  218. static std::string convert(signed char c);
  219. };
  220. template<>
  221. struct StringMaker<unsigned char> {
  222. static std::string convert(unsigned char c);
  223. };
  224. template<>
  225. struct StringMaker<std::nullptr_t> {
  226. static std::string convert(std::nullptr_t);
  227. };
  228. template<>
  229. struct StringMaker<float> {
  230. static std::string convert(float value);
  231. static int precision;
  232. };
  233. template<>
  234. struct StringMaker<double> {
  235. static std::string convert(double value);
  236. static int precision;
  237. };
  238. template <typename T>
  239. struct StringMaker<T*> {
  240. template <typename U>
  241. static std::string convert(U* p) {
  242. if (p) {
  243. return ::Catch::Detail::rawMemoryToString(p);
  244. } else {
  245. return "nullptr";
  246. }
  247. }
  248. };
  249. template <typename R, typename C>
  250. struct StringMaker<R C::*> {
  251. static std::string convert(R C::* p) {
  252. if (p) {
  253. return ::Catch::Detail::rawMemoryToString(p);
  254. } else {
  255. return "nullptr";
  256. }
  257. }
  258. };
  259. #if defined(_MANAGED)
  260. template <typename T>
  261. struct StringMaker<T^> {
  262. static std::string convert( T^ ref ) {
  263. return ::Catch::Detail::clrReferenceToString(ref);
  264. }
  265. };
  266. #endif
  267. namespace Detail {
  268. template<typename InputIterator, typename Sentinel = InputIterator>
  269. std::string rangeToString(InputIterator first, Sentinel last) {
  270. ReusableStringStream rss;
  271. rss << "{ ";
  272. if (first != last) {
  273. rss << ::Catch::Detail::stringify(*first);
  274. for (++first; first != last; ++first)
  275. rss << ", " << ::Catch::Detail::stringify(*first);
  276. }
  277. rss << " }";
  278. return rss.str();
  279. }
  280. }
  281. #ifdef __OBJC__
  282. template<>
  283. struct StringMaker<NSString*> {
  284. static std::string convert(NSString * nsstring) {
  285. if (!nsstring)
  286. return "nil";
  287. return std::string("@") + [nsstring UTF8String];
  288. }
  289. };
  290. template<>
  291. struct StringMaker<NSObject*> {
  292. static std::string convert(NSObject* nsObject) {
  293. return ::Catch::Detail::stringify([nsObject description]);
  294. }
  295. };
  296. namespace Detail {
  297. inline std::string stringify( NSString* nsstring ) {
  298. return StringMaker<NSString*>::convert( nsstring );
  299. }
  300. } // namespace Detail
  301. #endif // __OBJC__
  302. } // namespace Catch
  303. //////////////////////////////////////////////////////
  304. // Separate std-lib types stringification, so it can be selectively enabled
  305. // This means that we do not bring in
  306. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  307. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  308. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  309. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  310. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  311. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  312. #endif
  313. // Separate std::pair specialization
  314. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  315. #include <utility>
  316. namespace Catch {
  317. template<typename T1, typename T2>
  318. struct StringMaker<std::pair<T1, T2> > {
  319. static std::string convert(const std::pair<T1, T2>& pair) {
  320. ReusableStringStream rss;
  321. rss << "{ "
  322. << ::Catch::Detail::stringify(pair.first)
  323. << ", "
  324. << ::Catch::Detail::stringify(pair.second)
  325. << " }";
  326. return rss.str();
  327. }
  328. };
  329. }
  330. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  331. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  332. #include <optional>
  333. namespace Catch {
  334. template<typename T>
  335. struct StringMaker<std::optional<T> > {
  336. static std::string convert(const std::optional<T>& optional) {
  337. ReusableStringStream rss;
  338. if (optional.has_value()) {
  339. rss << ::Catch::Detail::stringify(*optional);
  340. } else {
  341. rss << "{ }";
  342. }
  343. return rss.str();
  344. }
  345. };
  346. }
  347. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  348. // Separate std::tuple specialization
  349. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  350. #include <tuple>
  351. namespace Catch {
  352. namespace Detail {
  353. template<
  354. typename Tuple,
  355. std::size_t N = 0,
  356. bool = (N < std::tuple_size<Tuple>::value)
  357. >
  358. struct TupleElementPrinter {
  359. static void print(const Tuple& tuple, std::ostream& os) {
  360. os << (N ? ", " : " ")
  361. << ::Catch::Detail::stringify(std::get<N>(tuple));
  362. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  363. }
  364. };
  365. template<
  366. typename Tuple,
  367. std::size_t N
  368. >
  369. struct TupleElementPrinter<Tuple, N, false> {
  370. static void print(const Tuple&, std::ostream&) {}
  371. };
  372. }
  373. template<typename ...Types>
  374. struct StringMaker<std::tuple<Types...>> {
  375. static std::string convert(const std::tuple<Types...>& tuple) {
  376. ReusableStringStream rss;
  377. rss << '{';
  378. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  379. rss << " }";
  380. return rss.str();
  381. }
  382. };
  383. }
  384. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  385. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  386. #include <variant>
  387. namespace Catch {
  388. template<>
  389. struct StringMaker<std::monostate> {
  390. static std::string convert(const std::monostate&) {
  391. return "{ }";
  392. }
  393. };
  394. template<typename... Elements>
  395. struct StringMaker<std::variant<Elements...>> {
  396. static std::string convert(const std::variant<Elements...>& variant) {
  397. if (variant.valueless_by_exception()) {
  398. return "{valueless variant}";
  399. } else {
  400. return std::visit(
  401. [](const auto& value) {
  402. return ::Catch::Detail::stringify(value);
  403. },
  404. variant
  405. );
  406. }
  407. }
  408. };
  409. }
  410. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  411. namespace Catch {
  412. // Import begin/ end from std here
  413. using std::begin;
  414. using std::end;
  415. namespace detail {
  416. template <typename...>
  417. struct void_type {
  418. using type = void;
  419. };
  420. template <typename T, typename = void>
  421. struct is_range_impl : std::false_type {
  422. };
  423. template <typename T>
  424. struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
  425. };
  426. } // namespace detail
  427. template <typename T>
  428. struct is_range : detail::is_range_impl<T> {
  429. };
  430. #if defined(_MANAGED) // Managed types are never ranges
  431. template <typename T>
  432. struct is_range<T^> {
  433. static const bool value = false;
  434. };
  435. #endif
  436. template<typename Range>
  437. std::string rangeToString( Range const& range ) {
  438. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  439. }
  440. // Handle vector<bool> specially
  441. template<typename Allocator>
  442. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  443. ReusableStringStream rss;
  444. rss << "{ ";
  445. bool first = true;
  446. for( bool b : v ) {
  447. if( first )
  448. first = false;
  449. else
  450. rss << ", ";
  451. rss << ::Catch::Detail::stringify( b );
  452. }
  453. rss << " }";
  454. return rss.str();
  455. }
  456. template<typename R>
  457. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  458. static std::string convert( R const& range ) {
  459. return rangeToString( range );
  460. }
  461. };
  462. template <typename T, int SZ>
  463. struct StringMaker<T[SZ]> {
  464. static std::string convert(T const(&arr)[SZ]) {
  465. return rangeToString(arr);
  466. }
  467. };
  468. } // namespace Catch
  469. // Separate std::chrono::duration specialization
  470. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  471. #include <ctime>
  472. #include <ratio>
  473. #include <chrono>
  474. namespace Catch {
  475. template <class Ratio>
  476. struct ratio_string {
  477. static std::string symbol();
  478. };
  479. template <class Ratio>
  480. std::string ratio_string<Ratio>::symbol() {
  481. Catch::ReusableStringStream rss;
  482. rss << '[' << Ratio::num << '/'
  483. << Ratio::den << ']';
  484. return rss.str();
  485. }
  486. template <>
  487. struct ratio_string<std::atto> {
  488. static std::string symbol();
  489. };
  490. template <>
  491. struct ratio_string<std::femto> {
  492. static std::string symbol();
  493. };
  494. template <>
  495. struct ratio_string<std::pico> {
  496. static std::string symbol();
  497. };
  498. template <>
  499. struct ratio_string<std::nano> {
  500. static std::string symbol();
  501. };
  502. template <>
  503. struct ratio_string<std::micro> {
  504. static std::string symbol();
  505. };
  506. template <>
  507. struct ratio_string<std::milli> {
  508. static std::string symbol();
  509. };
  510. ////////////
  511. // std::chrono::duration specializations
  512. template<typename Value, typename Ratio>
  513. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  514. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  515. ReusableStringStream rss;
  516. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  517. return rss.str();
  518. }
  519. };
  520. template<typename Value>
  521. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  522. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  523. ReusableStringStream rss;
  524. rss << duration.count() << " s";
  525. return rss.str();
  526. }
  527. };
  528. template<typename Value>
  529. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  530. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  531. ReusableStringStream rss;
  532. rss << duration.count() << " m";
  533. return rss.str();
  534. }
  535. };
  536. template<typename Value>
  537. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  538. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  539. ReusableStringStream rss;
  540. rss << duration.count() << " h";
  541. return rss.str();
  542. }
  543. };
  544. ////////////
  545. // std::chrono::time_point specialization
  546. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  547. template<typename Clock, typename Duration>
  548. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  549. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  550. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  551. }
  552. };
  553. // std::chrono::time_point<system_clock> specialization
  554. template<typename Duration>
  555. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  556. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  557. auto converted = std::chrono::system_clock::to_time_t(time_point);
  558. #ifdef _MSC_VER
  559. std::tm timeInfo = {};
  560. gmtime_s(&timeInfo, &converted);
  561. #else
  562. std::tm* timeInfo = std::gmtime(&converted);
  563. #endif
  564. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  565. char timeStamp[timeStampSize];
  566. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  567. #ifdef _MSC_VER
  568. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  569. #else
  570. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  571. #endif
  572. return std::string(timeStamp);
  573. }
  574. };
  575. }
  576. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  577. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  578. namespace Catch { \
  579. template<> struct StringMaker<enumName> { \
  580. static std::string convert( enumName value ) { \
  581. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  582. return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
  583. } \
  584. }; \
  585. }
  586. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  587. #ifdef _MSC_VER
  588. #pragma warning(pop)
  589. #endif
  590. #endif // TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED