You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
6.4 KiB

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