ostream.h 7.4 KB

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