libstdc++
print.h
Go to the documentation of this file.
1// Inline implementation details for std::print functions -*- C++ -*-
2
3// Copyright The GNU Toolchain Authors.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/bits/print.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{print}
28 *
29 * This file contains the parts of `<print>` which are currently defined
30 * inline, but should be moved into the library eventually.
31 */
32
33#ifndef _GLIBCXX_PRINT_H
34#define _GLIBCXX_PRINT_H 1
35
36#ifdef _GLIBCXX_SYSHDR
37#pragma GCC system_header
38#endif
39
40#include <bits/requires_hosted.h> // for std::format
41
42#include <bits/version.h>
43
44#ifdef __glibcxx_print // C++ >= 23
45
46#include <format>
47#include <cstdio> // FILE, EOF, flockfile, etc.
48#include <cerrno> // EACCES, EIO
49#include <bits/functexcept.h> // __throw_system_error
50
51#ifdef _WIN32
52# include <system_error> // system_error
53#endif
54
55namespace std _GLIBCXX_VISIBILITY(default)
56{
57_GLIBCXX_BEGIN_NAMESPACE_VERSION
58
59namespace __format
60{
61#if _GLIBCXX_USE_STDIO_LOCKING && _GLIBCXX_USE_GLIBC_STDIO_EXT
62 // These are defined in <stdio_ext.h> but we don't want to include that.
63 extern "C" int __fwritable(FILE*) noexcept;
64 extern "C" int __flbf(FILE*) noexcept;
65 extern "C" size_t __fbufsize(FILE*) noexcept;
66
67 // A format sink that writes directly to a Glibc FILE.
68 // The file is locked on construction and its buffer is accessed directly.
69 class _File_sink final : _Buf_sink<char>
70 {
71 struct _File
72 {
73 explicit
74 _File(FILE* __f) : _M_file(__f)
75 {
76 ::flockfile(__f);
77 // Ensure stream is in write mode
78 if (!__fwritable(__f))
79 {
80 ::funlockfile(__f);
81 __throw_system_error(EACCES);
82 }
83 }
84
85 ~_File() { ::funlockfile(_M_file); }
86
87 _File(_File&&) = delete;
88
89 // Allocate FILE's output buffer if needed, and return a span
90 // viewing unused portion of it.
91 std::span<char>
92 _M_init_write_buf()
93 {
94 // After setvbuf glibc pre-allocates the buffer but _IO_write_ptr
95 // remains null until the first write.
96 if (!_M_file->_IO_write_ptr || _M_write_buf().empty())
97 if (::__overflow(_M_file, EOF) == EOF)
98 __throw_system_error(errno);
99 return _M_write_buf();
100 }
101
102 // A span viewing the unused portion of the stream's output buffer.
103 std::span<char>
104 _M_write_buf() noexcept
105 {
106 return {_M_file->_IO_write_ptr,
107 size_t(_M_file->_IO_buf_end - _M_file->_IO_write_ptr)};
108 }
109
110 // Flush the output buffer to the file so we can write to it again.
111 void
112 _M_flush()
113 {
114 if (::fflush_unlocked(_M_file))
115 __throw_system_error(errno);
116 }
117
118 // Update the current position in the output buffer.
119 // __n is the number of characters written to the _M_write_buf() span,
120 // so will not exceed the size of the output buffer.
121 void
122 _M_bump(size_t __n) noexcept
123 { _M_file->_IO_write_ptr += __n; }
124
125 bool
126 _M_line_buffered() const noexcept
127 { return __flbf(_M_file); } // Or: _M_file->_flags & 0x200
128
129 bool
130 _M_unbuffered() const noexcept
131 { return __fbufsize(_M_file) == 1; } // Or: _M_file->_flags & 0x2
132
133 FILE* _M_file;
134 } _M_file;
135
136 bool _M_add_newline; // True for std::println, false for std::print.
137
138 // Flush the stream's put area so it can be refilled.
139 void
140 _M_overflow() override
141 {
142 auto __s = this->_M_used();
143 if (__s.data() == this->_M_buf)
144 {
145 // Characters in internal buffer need to be transferred to the FILE.
146 auto __n = ::fwrite_unlocked(__s.data(), 1, __s.size(),
147 _M_file._M_file);
148 if (__n != __s.size())
149 __throw_system_error(errno);
150 this->_M_reset(this->_M_buf);
151 }
152 else
153 {
154 // Characters were written directly to the FILE's output buffer.
155 _M_file._M_bump(__s.size());
156 _M_file._M_flush();
157 this->_M_reset(_M_file._M_write_buf());
158 }
159 }
160
161 public:
162 _File_sink(FILE* __f, bool __add_newline)
163 : _M_file(__f), _M_add_newline(__add_newline)
164 {
165 if (!_M_file._M_unbuffered())
166 // Allocate FILE's output buffer if needed, and write directly to it.
167 this->_M_reset(_M_file._M_init_write_buf());
168 }
169
170 // This calls I/O functions which are cancellation points, so they
171 // could exit with a __forced_unwind exception. The noexcept(false)
172 // allows that to propagate instead of terminating the process.
173 ~_File_sink() noexcept(false)
174 {
175 auto __s = this->_M_used();
176 if (__s.data() == this->_M_buf) // Unbuffered stream
177 {
178 _File_sink::_M_overflow(); // Transfer _M_buf to stream.
179 if (_M_add_newline)
180 ::putc_unlocked('\n', _M_file._M_file);
181 }
182 else
183 {
184 _M_file._M_bump(__s.size());
185 if (_M_add_newline)
186 ::putc_unlocked('\n', _M_file._M_file); // '\n' triggers a flush
187 else if (_M_file._M_line_buffered() && __s.size()
188 && (__s.back() == '\n'
189 || __builtin_memchr(__s.data(), '\n', __s.size())))
190 _M_file._M_flush();
191 }
192 }
193
194 using _Sink<char>::out;
195 };
196#elif _GLIBCXX_USE_STDIO_LOCKING
197 // A format sink that buffers output and then copies it to a stdio FILE.
198 // The file is locked on construction and written to using fwrite_unlocked.
199 class _File_sink final : _Buf_sink<char>
200 {
201 struct _File // RAII type to lock/unlock the file.
202 {
203 explicit _File(FILE* __f) : _M_file(__f) { ::flockfile(_M_file); }
204 ~_File() { ::funlockfile(_M_file); }
205 FILE* _M_file;
206 } _M_file;
207
208 bool _M_add_newline;
209
210 // Transfer buffer contents to the FILE, so buffer can be refilled.
211 void
212 _M_overflow() override
213 {
214 auto __s = this->_M_used();
215#if _GLIBCXX_HAVE_FWRITE_UNLOCKED
216 auto __n = ::fwrite_unlocked(__s.data(), 1, __s.size(), _M_file._M_file);
217 if (__n != __s.size())
218 __throw_system_error(errno);
219#else
220 for (char __c : __s)
221 ::putc_unlocked(__c, _M_file._M_file);
222 if (::ferror(_M_file._M_file))
223 __throw_system_error(errno);
224#endif
225 this->_M_reset(this->_M_buf);
226 }
227
228 public:
229 _File_sink(FILE* __f, bool __add_newline) noexcept
230 : _Buf_sink<char>(), _M_file(__f), _M_add_newline(__add_newline)
231 { }
232
233 ~_File_sink() noexcept(false) // See above for noexcept(false) rationale.
234 {
235 _File_sink::_M_overflow();
236 if (_M_add_newline)
237 ::putc_unlocked('\n', _M_file._M_file);
238 }
239
240 using _Sink<char>::out;
241 };
242#else
243 // A wrapper around a format sink that copies the output to a stdio FILE.
244 // This is not actually a _Sink itself, but it creates one to hold the
245 // formatted characters and then copies them to the file when finished.
246 class _File_sink final
247 {
248 FILE* _M_file;
249 _Str_sink<char> _M_sink;
250 bool _M_add_newline;
251
252 public:
253 _File_sink(FILE* __f, bool __add_newline) noexcept
254 : _M_file(__f), _M_add_newline(__add_newline)
255 { }
256
257 ~_File_sink() noexcept(false) // See above for noexcept(false) rationale.
258 {
259 string __s = std::move(_M_sink).get();
260 if (_M_add_newline)
261 __s += '\n';
262 auto __n = std::fwrite(__s.data(), 1, __s.size(), _M_file);
263 if (__n < __s.size())
264 __throw_system_error(EIO); // Non-POSIX fwrite doesn't set errno.
265 }
266
267 auto out() { return _M_sink.out(); }
268 };
269#endif
270} // namespace __format
271
272#ifdef _GLIBCXX_NO_INLINE_PRINT
273# define _GLIBCXX_PRINT_INLINE_USED [[__gnu__::__used__]]
274#else
275# define _GLIBCXX_PRINT_INLINE_USED
276#endif
277
278 _GLIBCXX_PRINT_INLINE_USED
279 inline void
280 vprint_nonunicode(FILE* __stream, string_view __fmt, format_args __args)
281 {
282 std::vformat_to(__format::_File_sink(__stream, false).out(), __fmt, __args);
283 }
284
285 _GLIBCXX_PRINT_INLINE_USED
286 inline void
287 vprint_nonunicode_buffered(FILE* __stream, string_view __fmt,
288 format_args __args)
289 {
290 // _GLIBCXX_RESOLVE_LIB_DEFECTS
291 // 4549. vprint_nonunicode_buffered ignores its stream parameter
292 __format::_Str_sink<char> __buf;
293 std::vformat_to(__buf.out(), __fmt, __args);
294 auto __out = __buf.view();
295 if (std::fwrite(__out.data(), 1, __out.size(), __stream) != __out.size())
296 __throw_system_error(EIO);
297 }
298
299 _GLIBCXX_PRINT_INLINE_USED
300 inline void
301 vprint_unicode(FILE* __stream, string_view __fmt, format_args __args)
302 {
303#if !defined(_WIN32) || defined(__CYGWIN__)
304 // For most targets we don't need to do anything special to write
305 // Unicode to a terminal.
306 std::vprint_nonunicode(__stream, __fmt, __args);
307#else
308 __format::_Str_sink<char> __buf;
309 std::vformat_to(__buf.out(), __fmt, __args);
310 auto __out = __buf._M_span();
311
312 void* __open_terminal(FILE*);
313 error_code __write_to_terminal(void*, span<char>);
314 // If stream refers to a terminal, write a native Unicode string to it.
315 if (auto __term = __open_terminal(__stream))
316 {
317 error_code __e;
318 if (!std::fflush(__stream))
319 {
320 __e = __write_to_terminal(__term, __out);
321 if (!__e)
322 return;
323 if (__e == std::make_error_code(errc::illegal_byte_sequence))
324 return;
325 }
326 else
327 __e = error_code(errno, generic_category());
328 _GLIBCXX_THROW_OR_ABORT(system_error(__e, "std::vprint_unicode"));
329 }
330
331 // Otherwise just write the string to the file.
332 if (std::fwrite(__out.data(), 1, __out.size(), __stream) != __out.size())
333 __throw_system_error(EIO);
334#endif
335 }
336
337 _GLIBCXX_PRINT_INLINE_USED
338 inline void
339 vprint_unicode_buffered(FILE* __stream, string_view __fmt, format_args __args)
340 {
341#if !defined(_WIN32) || defined(__CYGWIN__)
342 // For most targets we don't need to do anything special to write
343 // Unicode to a terminal. Just use the nonunicode function.
344 std::vprint_nonunicode_buffered(__stream, __fmt, __args);
345#else
346 // For Windows the locking function formats everything first anyway,
347 // so no formatting happens while a lock is taken. Just use that.
348 std::vprint_unicode(__stream, __fmt, __args);
349#endif
350 }
351#undef _GLIBCXX_PRINT_INLINE_USED
352
353_GLIBCXX_END_NAMESPACE_VERSION
354} // namespace std
355#endif // __glibcxx_print
356#endif // _GLIBCXX_PRINT_H
const error_category & generic_category() noexcept
Error category for errno error codes.
error_code make_error_code(future_errc __errc) noexcept
Overload of make_error_code for future_errc.
Definition future:96
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
ISO C++ entities toplevel namespace is std.
An exception type that includes an error_code value.
Definition system_error:559