1 // Formatting library for C++ - optional OS-specific functionality
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7
8 #ifndef FMT_OS_H_
9 #define FMT_OS_H_
10
11 #include <cerrno>
12 #include <cstddef>
13 #include <cstdio>
14 #include <system_error> // std::system_error
15
16 #include "format.h"
17
18 #if defined __APPLE__ || defined(__FreeBSD__)
19 # if FMT_HAS_INCLUDE(<xlocale.h>)
20 # include <xlocale.h> // for LC_NUMERIC_MASK on OS X
21 # endif
22 #endif
23
24 #ifndef FMT_USE_FCNTL
25 // UWP doesn't provide _pipe.
26 # if FMT_HAS_INCLUDE("winapifamily.h")
27 # include <winapifamily.h>
28 # endif
29 # if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
30 defined(__linux__)) && \
31 (!defined(WINAPI_FAMILY) || \
32 (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
33 # include <fcntl.h> // for O_RDONLY
34 # define FMT_USE_FCNTL 1
35 # else
36 # define FMT_USE_FCNTL 0
37 # endif
38 #endif
39
40 #ifndef FMT_POSIX
41 # if defined(_WIN32) && !defined(__MINGW32__)
42 // Fix warnings about deprecated symbols.
43 # define FMT_POSIX(call) _##call
44 # else
45 # define FMT_POSIX(call) call
46 # endif
47 #endif
48
49 // Calls to system functions are wrapped in FMT_SYSTEM for testability.
50 #ifdef FMT_SYSTEM
51 # define FMT_HAS_SYSTEM
52 # define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
53 #else
54 # define FMT_SYSTEM(call) ::call
55 # ifdef _WIN32
56 // Fix warnings about deprecated symbols.
57 # define FMT_POSIX_CALL(call) ::_##call
58 # else
59 # define FMT_POSIX_CALL(call) ::call
60 # endif
61 #endif
62
63 // Retries the expression while it evaluates to error_result and errno
64 // equals to EINTR.
65 #ifndef _WIN32
66 # define FMT_RETRY_VAL(result, expression, error_result) \
67 do { \
68 (result) = (expression); \
69 } while ((result) == (error_result) && errno == EINTR)
70 #else
71 # define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
72 #endif
73
74 #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
75
76 FMT_BEGIN_NAMESPACE
77 FMT_BEGIN_EXPORT
78
79 /**
80 \rst
81 A reference to a null-terminated string. It can be constructed from a C
82 string or ``std::string``.
83
84 You can use one of the following type aliases for common character types:
85
86 +---------------+-----------------------------+
87 | Type | Definition |
88 +===============+=============================+
89 | cstring_view | basic_cstring_view<char> |
90 +---------------+-----------------------------+
91 | wcstring_view | basic_cstring_view<wchar_t> |
92 +---------------+-----------------------------+
93
94 This class is most useful as a parameter type to allow passing
95 different types of strings to a function, for example::
96
97 template <typename... Args>
98 std::string format(cstring_view format_str, const Args & ... args);
99
100 format("{}", 42);
101 format(std::string("{}"), 42);
102 \endrst
103 */
104 template <typename Char> class basic_cstring_view {
105 private:
106 const Char* data_;
107
108 public:
109 /** Constructs a string reference object from a C string. */
basic_cstring_view(const Char * s)110 basic_cstring_view(const Char* s) : data_(s) {}
111
112 /**
113 \rst
114 Constructs a string reference from an ``std::string`` object.
115 \endrst
116 */
basic_cstring_view(const std::basic_string<Char> & s)117 basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
118
119 /** Returns the pointer to a C string. */
120 auto c_str() const -> const Char* { return data_; }
121 };
122
123 using cstring_view = basic_cstring_view<char>;
124 using wcstring_view = basic_cstring_view<wchar_t>;
125
126 #ifdef _WIN32
127 FMT_API const std::error_category& system_category() noexcept;
128
129 namespace detail {
130 FMT_API void format_windows_error(buffer<char>& out, int error_code,
131 const char* message) noexcept;
132 }
133
134 FMT_API std::system_error vwindows_error(int error_code, string_view format_str,
135 format_args args);
136
137 /**
138 \rst
139 Constructs a :class:`std::system_error` object with the description
140 of the form
141
142 .. parsed-literal::
143 *<message>*: *<system-message>*
144
145 where *<message>* is the formatted message and *<system-message>* is the
146 system message corresponding to the error code.
147 *error_code* is a Windows error code as given by ``GetLastError``.
148 If *error_code* is not a valid error code such as -1, the system message
149 will look like "error -1".
150
151 **Example**::
152
153 // This throws a system_error with the description
154 // cannot open file 'madeup': The system cannot find the file specified.
155 // or similar (system message may vary).
156 const char *filename = "madeup";
157 LPOFSTRUCT of = LPOFSTRUCT();
158 HFILE file = OpenFile(filename, &of, OF_READ);
159 if (file == HFILE_ERROR) {
160 throw fmt::windows_error(GetLastError(),
161 "cannot open file '{}'", filename);
162 }
163 \endrst
164 */
165 template <typename... Args>
windows_error(int error_code,string_view message,const Args &...args)166 std::system_error windows_error(int error_code, string_view message,
167 const Args&... args) {
168 return vwindows_error(error_code, message, fmt::make_format_args(args...));
169 }
170
171 // Reports a Windows error without throwing an exception.
172 // Can be used to report errors from destructors.
173 FMT_API void report_windows_error(int error_code, const char* message) noexcept;
174 #else
175 inline auto system_category() noexcept -> const std::error_category& {
176 return std::system_category();
177 }
178 #endif // _WIN32
179
180 // std::system is not available on some platforms such as iOS (#2248).
181 #ifdef __OSX__
182 template <typename S, typename... Args, typename Char = char_t<S>>
say(const S & format_str,Args &&...args)183 void say(const S& format_str, Args&&... args) {
184 std::system(format("say \"{}\"", format(format_str, args...)).c_str());
185 }
186 #endif
187
188 // A buffered file.
189 class buffered_file {
190 private:
191 FILE* file_;
192
193 friend class file;
194
buffered_file(FILE * f)195 explicit buffered_file(FILE* f) : file_(f) {}
196
197 public:
198 buffered_file(const buffered_file&) = delete;
199 void operator=(const buffered_file&) = delete;
200
201 // Constructs a buffered_file object which doesn't represent any file.
buffered_file()202 buffered_file() noexcept : file_(nullptr) {}
203
204 // Destroys the object closing the file it represents if any.
205 FMT_API ~buffered_file() noexcept;
206
207 public:
buffered_file(buffered_file && other)208 buffered_file(buffered_file&& other) noexcept : file_(other.file_) {
209 other.file_ = nullptr;
210 }
211
212 auto operator=(buffered_file&& other) -> buffered_file& {
213 close();
214 file_ = other.file_;
215 other.file_ = nullptr;
216 return *this;
217 }
218
219 // Opens a file.
220 FMT_API buffered_file(cstring_view filename, cstring_view mode);
221
222 // Closes the file.
223 FMT_API void close();
224
225 // Returns the pointer to a FILE object representing this file.
226 auto get() const noexcept -> FILE* { return file_; }
227
228 FMT_API auto descriptor() const -> int;
229
vprint(string_view format_str,format_args args)230 void vprint(string_view format_str, format_args args) {
231 fmt::vprint(file_, format_str, args);
232 }
233
234 template <typename... Args>
print(string_view format_str,const Args &...args)235 inline void print(string_view format_str, const Args&... args) {
236 vprint(format_str, fmt::make_format_args(args...));
237 }
238 };
239
240 #if FMT_USE_FCNTL
241 // A file. Closed file is represented by a file object with descriptor -1.
242 // Methods that are not declared with noexcept may throw
243 // fmt::system_error in case of failure. Note that some errors such as
244 // closing the file multiple times will cause a crash on Windows rather
245 // than an exception. You can get standard behavior by overriding the
246 // invalid parameter handler with _set_invalid_parameter_handler.
247 class FMT_API file {
248 private:
249 int fd_; // File descriptor.
250
251 // Constructs a file object with a given descriptor.
file(int fd)252 explicit file(int fd) : fd_(fd) {}
253
254 public:
255 // Possible values for the oflag argument to the constructor.
256 enum {
257 RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
258 WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
259 RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing.
260 CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist.
261 APPEND = FMT_POSIX(O_APPEND), // Open in append mode.
262 TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file.
263 };
264
265 // Constructs a file object which doesn't represent any file.
file()266 file() noexcept : fd_(-1) {}
267
268 // Opens a file and constructs a file object representing this file.
269 file(cstring_view path, int oflag);
270
271 public:
272 file(const file&) = delete;
273 void operator=(const file&) = delete;
274
file(file && other)275 file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }
276
277 // Move assignment is not noexcept because close may throw.
278 auto operator=(file&& other) -> file& {
279 close();
280 fd_ = other.fd_;
281 other.fd_ = -1;
282 return *this;
283 }
284
285 // Destroys the object closing the file it represents if any.
286 ~file() noexcept;
287
288 // Returns the file descriptor.
289 auto descriptor() const noexcept -> int { return fd_; }
290
291 // Closes the file.
292 void close();
293
294 // Returns the file size. The size has signed type for consistency with
295 // stat::st_size.
296 auto size() const -> long long;
297
298 // Attempts to read count bytes from the file into the specified buffer.
299 auto read(void* buffer, size_t count) -> size_t;
300
301 // Attempts to write count bytes from the specified buffer to the file.
302 auto write(const void* buffer, size_t count) -> size_t;
303
304 // Duplicates a file descriptor with the dup function and returns
305 // the duplicate as a file object.
306 static auto dup(int fd) -> file;
307
308 // Makes fd be the copy of this file descriptor, closing fd first if
309 // necessary.
310 void dup2(int fd);
311
312 // Makes fd be the copy of this file descriptor, closing fd first if
313 // necessary.
314 void dup2(int fd, std::error_code& ec) noexcept;
315
316 // Creates a pipe setting up read_end and write_end file objects for reading
317 // and writing respectively.
318 // DEPRECATED! Taking files as out parameters is deprecated.
319 static void pipe(file& read_end, file& write_end);
320
321 // Creates a buffered_file object associated with this file and detaches
322 // this file object from the file.
323 auto fdopen(const char* mode) -> buffered_file;
324
325 # if defined(_WIN32) && !defined(__MINGW32__)
326 // Opens a file and constructs a file object representing this file by
327 // wcstring_view filename. Windows only.
328 static file open_windows_file(wcstring_view path, int oflag);
329 # endif
330 };
331
332 // Returns the memory page size.
333 auto getpagesize() -> long;
334
335 namespace detail {
336
337 struct buffer_size {
338 buffer_size() = default;
339 size_t value = 0;
340 auto operator=(size_t val) const -> buffer_size {
341 auto bs = buffer_size();
342 bs.value = val;
343 return bs;
344 }
345 };
346
347 struct ostream_params {
348 int oflag = file::WRONLY | file::CREATE | file::TRUNC;
349 size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;
350
ostream_paramsostream_params351 ostream_params() {}
352
353 template <typename... T>
ostream_paramsostream_params354 ostream_params(T... params, int new_oflag) : ostream_params(params...) {
355 oflag = new_oflag;
356 }
357
358 template <typename... T>
ostream_paramsostream_params359 ostream_params(T... params, detail::buffer_size bs)
360 : ostream_params(params...) {
361 this->buffer_size = bs.value;
362 }
363
364 // Intel has a bug that results in failure to deduce a constructor
365 // for empty parameter packs.
366 # if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
ostream_paramsostream_params367 ostream_params(int new_oflag) : oflag(new_oflag) {}
ostream_paramsostream_params368 ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {}
369 # endif
370 };
371
372 class file_buffer final : public buffer<char> {
373 file file_;
374
375 FMT_API void grow(size_t) override;
376
377 public:
378 FMT_API file_buffer(cstring_view path, const ostream_params& params);
379 FMT_API file_buffer(file_buffer&& other);
380 FMT_API ~file_buffer();
381
flush()382 void flush() {
383 if (size() == 0) return;
384 file_.write(data(), size() * sizeof(data()[0]));
385 clear();
386 }
387
close()388 void close() {
389 flush();
390 file_.close();
391 }
392 };
393
394 } // namespace detail
395
396 // Added {} below to work around default constructor error known to
397 // occur in Xcode versions 7.2.1 and 8.2.1.
398 constexpr detail::buffer_size buffer_size{};
399
400 /** A fast output stream which is not thread-safe. */
401 class FMT_API ostream {
402 private:
403 FMT_MSC_WARNING(suppress : 4251)
404 detail::file_buffer buffer_;
405
ostream(cstring_view path,const detail::ostream_params & params)406 ostream(cstring_view path, const detail::ostream_params& params)
407 : buffer_(path, params) {}
408
409 public:
ostream(ostream && other)410 ostream(ostream&& other) : buffer_(std::move(other.buffer_)) {}
411
412 ~ostream();
413
flush()414 void flush() { buffer_.flush(); }
415
416 template <typename... T>
417 friend auto output_file(cstring_view path, T... params) -> ostream;
418
close()419 void close() { buffer_.close(); }
420
421 /**
422 Formats ``args`` according to specifications in ``fmt`` and writes the
423 output to the file.
424 */
print(format_string<T...> fmt,T &&...args)425 template <typename... T> void print(format_string<T...> fmt, T&&... args) {
426 vformat_to(std::back_inserter(buffer_), fmt,
427 fmt::make_format_args(args...));
428 }
429 };
430
431 /**
432 \rst
433 Opens a file for writing. Supported parameters passed in *params*:
434
435 * ``<integer>``: Flags passed to `open
436 <https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
437 (``file::WRONLY | file::CREATE | file::TRUNC`` by default)
438 * ``buffer_size=<integer>``: Output buffer size
439
440 **Example**::
441
442 auto out = fmt::output_file("guide.txt");
443 out.print("Don't {}", "Panic");
444 \endrst
445 */
446 template <typename... T>
447 inline auto output_file(cstring_view path, T... params) -> ostream {
448 return {path, detail::ostream_params(params...)};
449 }
450 #endif // FMT_USE_FCNTL
451
452 FMT_END_EXPORT
453 FMT_END_NAMESPACE
454
455 #endif // FMT_OS_H_
456