ostream.h 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // Formatting library for C++ - std::ostream support
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #ifndef FMT_OSTREAM_H_
  8. #define FMT_OSTREAM_H_
  9. #ifndef FMT_MODULE
  10. # include <fstream> // std::filebuf
  11. #endif
  12. #ifdef _WIN32
  13. # ifdef __GLIBCXX__
  14. # include <ext/stdio_filebuf.h>
  15. # include <ext/stdio_sync_filebuf.h>
  16. # endif
  17. # include <io.h>
  18. #endif
  19. #include "chrono.h" // formatbuf
  20. FMT_BEGIN_NAMESPACE
  21. namespace detail {
  22. // Generate a unique explicit instantion in every translation unit using a tag
  23. // type in an anonymous namespace.
  24. namespace {
  25. struct file_access_tag {};
  26. } // namespace
  27. template <typename Tag, typename BufType, FILE* BufType::*FileMemberPtr>
  28. class file_access {
  29. friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; }
  30. };
  31. #if FMT_MSC_VERSION
  32. template class file_access<file_access_tag, std::filebuf,
  33. &std::filebuf::_Myfile>;
  34. auto get_file(std::filebuf&) -> FILE*;
  35. #endif
  36. inline auto write_ostream_unicode(std::ostream& os, fmt::string_view data)
  37. -> bool {
  38. FILE* f = nullptr;
  39. #if FMT_MSC_VERSION && FMT_USE_RTTI
  40. if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf()))
  41. f = get_file(*buf);
  42. else
  43. return false;
  44. #elif defined(_WIN32) && defined(__GLIBCXX__) && FMT_USE_RTTI
  45. auto* rdbuf = os.rdbuf();
  46. if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf))
  47. f = sfbuf->file();
  48. else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf))
  49. f = fbuf->file();
  50. else
  51. return false;
  52. #else
  53. ignore_unused(os, data, f);
  54. #endif
  55. #ifdef _WIN32
  56. if (f) {
  57. int fd = _fileno(f);
  58. if (_isatty(fd)) {
  59. os.flush();
  60. return write_console(fd, data);
  61. }
  62. }
  63. #endif
  64. return false;
  65. }
  66. inline auto write_ostream_unicode(std::wostream&,
  67. fmt::basic_string_view<wchar_t>) -> bool {
  68. return false;
  69. }
  70. // Write the content of buf to os.
  71. // It is a separate function rather than a part of vprint to simplify testing.
  72. template <typename Char>
  73. void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
  74. const Char* buf_data = buf.data();
  75. using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
  76. unsigned_streamsize size = buf.size();
  77. unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
  78. do {
  79. unsigned_streamsize n = size <= max_size ? size : max_size;
  80. os.write(buf_data, static_cast<std::streamsize>(n));
  81. buf_data += n;
  82. size -= n;
  83. } while (size != 0);
  84. }
  85. template <typename Char, typename T>
  86. void format_value(buffer<Char>& buf, const T& value) {
  87. auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
  88. auto&& output = std::basic_ostream<Char>(&format_buf);
  89. #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
  90. output.imbue(std::locale::classic()); // The default is always unlocalized.
  91. #endif
  92. output << value;
  93. output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
  94. }
  95. template <typename T> struct streamed_view {
  96. const T& value;
  97. };
  98. } // namespace detail
  99. // Formats an object of type T that has an overloaded ostream operator<<.
  100. template <typename Char>
  101. struct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> {
  102. void set_debug_format() = delete;
  103. template <typename T, typename Context>
  104. auto format(const T& value, Context& ctx) const -> decltype(ctx.out()) {
  105. auto buffer = basic_memory_buffer<Char>();
  106. detail::format_value(buffer, value);
  107. return formatter<basic_string_view<Char>, Char>::format(
  108. {buffer.data(), buffer.size()}, ctx);
  109. }
  110. };
  111. using ostream_formatter = basic_ostream_formatter<char>;
  112. template <typename T, typename Char>
  113. struct formatter<detail::streamed_view<T>, Char>
  114. : basic_ostream_formatter<Char> {
  115. template <typename Context>
  116. auto format(detail::streamed_view<T> view, Context& ctx) const
  117. -> decltype(ctx.out()) {
  118. return basic_ostream_formatter<Char>::format(view.value, ctx);
  119. }
  120. };
  121. /**
  122. * Returns a view that formats `value` via an ostream `operator<<`.
  123. *
  124. * **Example**:
  125. *
  126. * fmt::print("Current thread id: {}\n",
  127. * fmt::streamed(std::this_thread::get_id()));
  128. */
  129. template <typename T>
  130. constexpr auto streamed(const T& value) -> detail::streamed_view<T> {
  131. return {value};
  132. }
  133. namespace detail {
  134. inline void vprint_directly(std::ostream& os, string_view format_str,
  135. format_args args) {
  136. auto buffer = memory_buffer();
  137. detail::vformat_to(buffer, format_str, args);
  138. detail::write_buffer(os, buffer);
  139. }
  140. } // namespace detail
  141. FMT_EXPORT template <typename Char>
  142. void vprint(std::basic_ostream<Char>& os,
  143. basic_string_view<type_identity_t<Char>> format_str,
  144. typename detail::vformat_args<Char>::type args) {
  145. auto buffer = basic_memory_buffer<Char>();
  146. detail::vformat_to(buffer, format_str, args);
  147. if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return;
  148. detail::write_buffer(os, buffer);
  149. }
  150. /**
  151. * Prints formatted data to the stream `os`.
  152. *
  153. * **Example**:
  154. *
  155. * fmt::print(cerr, "Don't {}!", "panic");
  156. */
  157. FMT_EXPORT template <typename... T>
  158. void print(std::ostream& os, format_string<T...> fmt, T&&... args) {
  159. const auto& vargs = fmt::make_format_args(args...);
  160. if (detail::use_utf8())
  161. vprint(os, fmt, vargs);
  162. else
  163. detail::vprint_directly(os, fmt, vargs);
  164. }
  165. FMT_EXPORT
  166. template <typename... Args>
  167. void print(std::wostream& os,
  168. basic_format_string<wchar_t, type_identity_t<Args>...> fmt,
  169. Args&&... args) {
  170. vprint(os, fmt, fmt::make_format_args<buffered_context<wchar_t>>(args...));
  171. }
  172. FMT_EXPORT template <typename... T>
  173. void println(std::ostream& os, format_string<T...> fmt, T&&... args) {
  174. fmt::print(os, "{}\n", fmt::format(fmt, std::forward<T>(args)...));
  175. }
  176. FMT_EXPORT
  177. template <typename... Args>
  178. void println(std::wostream& os,
  179. basic_format_string<wchar_t, type_identity_t<Args>...> fmt,
  180. Args&&... args) {
  181. print(os, L"{}\n", fmt::format(fmt, std::forward<Args>(args)...));
  182. }
  183. FMT_END_NAMESPACE
  184. #endif // FMT_OSTREAM_H_