spdlog
Loading...
Searching...
No Matches
fmt/bundled/os.h
Go to the documentation of this file.
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 <clocale> // locale_t
13#include <cstddef>
14#include <cstdio>
15#include <cstdlib> // strtod_l
16#include <system_error> // std::system_error
17
18#if defined __APPLE__ || defined(__FreeBSD__)
19# include <xlocale.h> // for LC_NUMERIC_MASK on OS X
20#endif
21
22#include "format.h"
23
24// UWP doesn't provide _pipe.
25#if FMT_HAS_INCLUDE("winapifamily.h")
26# include <winapifamily.h>
27#endif
28#if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
29 defined(__linux__)) && \
30 (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
31# include <fcntl.h> // for O_RDONLY
32# define FMT_USE_FCNTL 1
33#else
34# define FMT_USE_FCNTL 0
35#endif
36
37#ifndef FMT_POSIX
38# if defined(_WIN32) && !defined(__MINGW32__)
39// Fix warnings about deprecated symbols.
40# define FMT_POSIX(call) _##call
41# else
42# define FMT_POSIX(call) call
43# endif
44#endif
45
46// Calls to system functions are wrapped in FMT_SYSTEM for testability.
47#ifdef FMT_SYSTEM
48# define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
49#else
50# define FMT_SYSTEM(call) ::call
51# ifdef _WIN32
52// Fix warnings about deprecated symbols.
53# define FMT_POSIX_CALL(call) ::_##call
54# else
55# define FMT_POSIX_CALL(call) ::call
56# endif
57#endif
58
59// Retries the expression while it evaluates to error_result and errno
60// equals to EINTR.
61#ifndef _WIN32
62# define FMT_RETRY_VAL(result, expression, error_result) \
63 do { \
64 (result) = (expression); \
65 } while ((result) == (error_result) && errno == EINTR)
66#else
67# define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
68#endif
69
70#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
71
74
75/**
76 \rst
77 A reference to a null-terminated string. It can be constructed from a C
78 string or ``std::string``.
79
80 You can use one of the following type aliases for common character types:
81
82 +---------------+-----------------------------+
83 | Type | Definition |
84 +===============+=============================+
85 | cstring_view | basic_cstring_view<char> |
86 +---------------+-----------------------------+
87 | wcstring_view | basic_cstring_view<wchar_t> |
88 +---------------+-----------------------------+
89
90 This class is most useful as a parameter type to allow passing
91 different types of strings to a function, for example::
92
93 template <typename... Args>
94 std::string format(cstring_view format_str, const Args & ... args);
95
96 format("{}", 42);
97 format(std::string("{}"), 42);
98 \endrst
99 */
100template <typename Char> class basic_cstring_view {
101 private:
102 const Char* data_;
103
104 public:
105 /** Constructs a string reference object from a C string. */
106 basic_cstring_view(const Char* s) : data_(s) {}
107
108 /**
109 \rst
110 Constructs a string reference from an ``std::string`` object.
111 \endrst
112 */
114
115 /** Returns the pointer to a C string. */
116 const Char* c_str() const { return data_; }
117};
118
121
122template <typename Char> struct formatter<std::error_code, Char> {
123 template <typename ParseContext>
124 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
125 return ctx.begin();
126 }
127
128 template <typename FormatContext>
129 FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const
130 -> decltype(ctx.out()) {
131 auto out = ctx.out();
132 out = detail::write_bytes(out, ec.category().name(),
134 out = detail::write<Char>(out, Char(':'));
135 out = detail::write<Char>(out, ec.value());
136 return out;
137 }
138};
139
140#ifdef _WIN32
142
144// A converter from UTF-16 to UTF-8.
145// It is only provided for Windows since other systems support UTF-8 natively.
146class utf16_to_utf8 {
147 private:
148 memory_buffer buffer_;
149
150 public:
151 utf16_to_utf8() {}
152 FMT_API explicit utf16_to_utf8(basic_string_view<wchar_t> s);
153 operator string_view() const { return string_view(&buffer_[0], size()); }
154 size_t size() const { return buffer_.size() - 1; }
155 const char* c_str() const { return &buffer_[0]; }
156 std::string str() const { return std::string(&buffer_[0], size()); }
157
158 // Performs conversion returning a system error code instead of
159 // throwing exception on conversion error. This method may still throw
160 // in case of memory allocation error.
161 FMT_API int convert(basic_string_view<wchar_t> s);
162};
163
164FMT_API void format_windows_error(buffer<char>& out, int error_code,
165 const char* message) FMT_NOEXCEPT;
167
168FMT_API std::system_error vwindows_error(int error_code, string_view format_str,
169 format_args args);
170
171/**
172 \rst
173 Constructs a :class:`std::system_error` object with the description
174 of the form
175
176 .. parsed-literal::
177 *<message>*: *<system-message>*
178
179 where *<message>* is the formatted message and *<system-message>* is the
180 system message corresponding to the error code.
181 *error_code* is a Windows error code as given by ``GetLastError``.
182 If *error_code* is not a valid error code such as -1, the system message
183 will look like "error -1".
184
185 **Example**::
186
187 // This throws a system_error with the description
188 // cannot open file 'madeup': The system cannot find the file specified.
189 // or similar (system message may vary).
190 const char *filename = "madeup";
191 LPOFSTRUCT of = LPOFSTRUCT();
192 HFILE file = OpenFile(filename, &of, OF_READ);
193 if (file == HFILE_ERROR) {
194 throw fmt::windows_error(GetLastError(),
195 "cannot open file '{}'", filename);
196 }
197 \endrst
198*/
199template <typename... Args>
200std::system_error windows_error(int error_code, string_view message,
201 const Args&... args) {
202 return vwindows_error(error_code, message, fmt::make_format_args(args...));
203}
204
205// Reports a Windows error without throwing an exception.
206// Can be used to report errors from destructors.
207FMT_API void report_windows_error(int error_code,
208 const char* message) FMT_NOEXCEPT;
209#else
213#endif // _WIN32
214
215// std::system is not available on some platforms such as iOS (#2248).
216#ifdef __OSX__
217template <typename S, typename... Args, typename Char = char_t<S>>
218void say(const S& format_str, Args&&... args) {
219 std::system(format("say \"{}\"", format(format_str, args...)).c_str());
220}
221#endif
222
223// A buffered file.
225 private:
226 FILE* file_;
227
228 friend class file;
229
230 explicit buffered_file(FILE* f) : file_(f) {}
231
232 public:
233 buffered_file(const buffered_file&) = delete;
234 void operator=(const buffered_file&) = delete;
235
236 // Constructs a buffered_file object which doesn't represent any file.
238
239 // Destroys the object closing the file it represents if any.
241
242 public:
244 other.file_ = nullptr;
245 }
246
248 close();
249 file_ = other.file_;
250 other.file_ = nullptr;
251 return *this;
252 }
253
254 // Opens a file.
256
257 // Closes the file.
259
260 // Returns the pointer to a FILE object representing this file.
261 FILE* get() const FMT_NOEXCEPT { return file_; }
262
263 // We place parentheses around fileno to workaround a bug in some versions
264 // of MinGW that define fileno as a macro.
266
267 void vprint(string_view format_str, format_args args) {
268 fmt::vprint(file_, format_str, args);
269 }
270
271 template <typename... Args>
272 inline void print(string_view format_str, const Args&... args) {
273 vprint(format_str, fmt::make_format_args(args...));
274 }
275};
276
277#if FMT_USE_FCNTL
278// A file. Closed file is represented by a file object with descriptor -1.
279// Methods that are not declared with FMT_NOEXCEPT may throw
280// fmt::system_error in case of failure. Note that some errors such as
281// closing the file multiple times will cause a crash on Windows rather
282// than an exception. You can get standard behavior by overriding the
283// invalid parameter handler with _set_invalid_parameter_handler.
284class file {
285 private:
286 int fd_; // File descriptor.
287
288 // Constructs a file object with a given descriptor.
289 explicit file(int fd) : fd_(fd) {}
290
291 public:
292 // Possible values for the oflag argument to the constructor.
293 enum {
294 RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
295 WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
296 RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing.
297 CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist.
298 APPEND = FMT_POSIX(O_APPEND), // Open in append mode.
299 TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file.
300 };
301
302 // Constructs a file object which doesn't represent any file.
303 file() FMT_NOEXCEPT : fd_(-1) {}
304
305 // Opens a file and constructs a file object representing this file.
306 FMT_API file(cstring_view path, int oflag);
307
308 public:
309 file(const file&) = delete;
310 void operator=(const file&) = delete;
311
312 file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
313
314 // Move assignment is not noexcept because close may throw.
315 file& operator=(file&& other) {
316 close();
317 fd_ = other.fd_;
318 other.fd_ = -1;
319 return *this;
320 }
321
322 // Destroys the object closing the file it represents if any.
323 FMT_API ~file() FMT_NOEXCEPT;
324
325 // Returns the file descriptor.
326 int descriptor() const FMT_NOEXCEPT { return fd_; }
327
328 // Closes the file.
329 FMT_API void close();
330
331 // Returns the file size. The size has signed type for consistency with
332 // stat::st_size.
333 FMT_API long long size() const;
334
335 // Attempts to read count bytes from the file into the specified buffer.
336 FMT_API size_t read(void* buffer, size_t count);
337
338 // Attempts to write count bytes from the specified buffer to the file.
339 FMT_API size_t write(const void* buffer, size_t count);
340
341 // Duplicates a file descriptor with the dup function and returns
342 // the duplicate as a file object.
343 FMT_API static file dup(int fd);
344
345 // Makes fd be the copy of this file descriptor, closing fd first if
346 // necessary.
347 FMT_API void dup2(int fd);
348
349 // Makes fd be the copy of this file descriptor, closing fd first if
350 // necessary.
351 FMT_API void dup2(int fd, std::error_code& ec) FMT_NOEXCEPT;
352
353 // Creates a pipe setting up read_end and write_end file objects for reading
354 // and writing respectively.
355 FMT_API static void pipe(file& read_end, file& write_end);
356
357 // Creates a buffered_file object associated with this file and detaches
358 // this file object from the file.
359 FMT_API buffered_file fdopen(const char* mode);
360};
361
362// Returns the memory page size.
363long getpagesize();
364
366
367struct buffer_size {
368 buffer_size() = default;
369 size_t value = 0;
370 buffer_size operator=(size_t val) const {
371 auto bs = buffer_size();
372 bs.value = val;
373 return bs;
374 }
375};
376
377struct ostream_params {
378 int oflag = file::WRONLY | file::CREATE | file::TRUNC;
379 size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;
380
381 ostream_params() {}
382
383 template <typename... T>
384 ostream_params(T... params, int new_oflag) : ostream_params(params...) {
385 oflag = new_oflag;
386 }
387
388 template <typename... T>
389 ostream_params(T... params, detail::buffer_size bs)
390 : ostream_params(params...) {
391 this->buffer_size = bs.value;
392 }
393};
394
396
397constexpr detail::buffer_size buffer_size;
398
399/** A fast output stream which is not thread-safe. */
400class FMT_API ostream final : private detail::buffer<char> {
401 private:
402 file file_;
403
404 void flush() {
405 if (size() == 0) return;
406 file_.write(data(), size());
407 clear();
408 }
409
410 void grow(size_t) override;
411
412 ostream(cstring_view path, const detail::ostream_params& params)
413 : file_(path, params.oflag) {
414 set(new char[params.buffer_size], params.buffer_size);
415 }
416
417 public:
418 ostream(ostream&& other)
419 : detail::buffer<char>(other.data(), other.size(), other.capacity()),
420 file_(std::move(other.file_)) {
421 other.clear();
422 other.set(nullptr, 0);
423 }
424 ~ostream() {
425 flush();
426 delete[] data();
427 }
428
429 template <typename... T>
430 friend ostream output_file(cstring_view path, T... params);
431
432 void close() {
433 flush();
434 file_.close();
435 }
436
437 /**
438 Formats ``args`` according to specifications in ``fmt`` and writes the
439 output to the file.
440 */
441 template <typename... T> void print(format_string<T...> fmt, T&&... args) {
442 vformat_to(detail::buffer_appender<char>(*this), fmt,
443 fmt::make_format_args(args...));
444 }
445};
446
447/**
448 \rst
449 Opens a file for writing. Supported parameters passed in *params*:
450
451 * ``<integer>``: Flags passed to `open
452 <https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
453 (``file::WRONLY | file::CREATE`` by default)
454 * ``buffer_size=<integer>``: Output buffer size
455
456 **Example**::
457
458 auto out = fmt::output_file("guide.txt");
459 out.print("Don't {}", "Panic");
460 \endrst
461 */
462template <typename... T>
463inline ostream output_file(cstring_view path, T... params) {
464 return {path, detail::ostream_params(params...)};
465}
466#endif // FMT_USE_FCNTL
467
468#ifdef FMT_LOCALE
469// A "C" numeric locale.
470class locale {
471 private:
472# ifdef _WIN32
473 using locale_t = _locale_t;
474
475 static void freelocale(locale_t loc) { _free_locale(loc); }
476
477 static double strtod_l(const char* nptr, char** endptr, _locale_t loc) {
478 return _strtod_l(nptr, endptr, loc);
479 }
480# endif
481
482 locale_t locale_;
483
484 public:
485 using type = locale_t;
486 locale(const locale&) = delete;
487 void operator=(const locale&) = delete;
488
489 locale() {
490# ifndef _WIN32
491 locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr));
492# else
493 locale_ = _create_locale(LC_NUMERIC, "C");
494# endif
495 if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
496 }
497 ~locale() { freelocale(locale_); }
498
499 type get() const { return locale_; }
500
501 // Converts string to floating-point number and advances str past the end
502 // of the parsed input.
503 double strtod(const char*& str) const {
504 char* end = nullptr;
505 double result = strtod_l(str, &end, locale_);
506 str = end;
507 return result;
508 }
509};
510using Locale FMT_DEPRECATED_ALIAS = locale;
511#endif // FMT_LOCALE
514
515#endif // FMT_OS_H_
basic_cstring_view(const std::basic_string< Char > &s)
basic_cstring_view(const Char *s)
const Char * c_str() const
Definition core.h:749
void vprint(string_view format_str, format_args args)
void operator=(const buffered_file &)=delete
FMT_API void close()
FILE * get() const FMT_NOEXCEPT
friend class file
buffered_file(FILE *f)
FMT_API buffered_file(cstring_view filename, cstring_view mode)
FMT_API int() fileno() const
buffered_file() FMT_NOEXCEPT
buffered_file(const buffered_file &)=delete
FMT_API ~buffered_file() FMT_NOEXCEPT
void print(string_view format_str, const Args &... args)
buffered_file & operator=(buffered_file &&other)
Definition core.h:1120
void print(std::FILE *f, const text_style &ts, const S &format_str, const Args &... args)
Definition color.h:538
void vformat_to(buffer< Char > &buf, const text_style &ts, basic_string_view< Char > format_str, basic_format_args< buffer_context< type_identity_t< Char > > > args)
Definition color.h:491
std::basic_string< Char > format(const text_style &ts, const S &format_str, const Args &... args)
Definition color.h:583
typename detail::char_t_impl< S >::type char_t
Definition core.h:610
#define FMT_END_DETAIL_NAMESPACE
Definition core.h:245
#define FMT_MODULE_EXPORT_BEGIN
Definition core.h:242
constexpr auto count() -> size_t
Definition core.h:1039
#define FMT_CONSTEXPR
Definition core.h:99
type
Definition core.h:1048
#define FMT_BEGIN_NAMESPACE
Definition core.h:235
#define FMT_BEGIN_DETAIL_NAMESPACE
Definition core.h:244
#define FMT_API
Definition core.h:264
T
Definition core.h:320
#define FMT_END_NAMESPACE
Definition core.h:230
#define FMT_MODULE_EXPORT_END
Definition core.h:243
#define FMT_NOEXCEPT
Definition core.h:156
T flush(T... args)
#define FMT_POSIX(call)
const std::error_category & system_category() FMT_NOEXCEPT
#define FMT_SYSTEM(call)
auto system_error(int error_code, format_string< T... > fmt, T &&... args) -> std::system_error
Definition format.h:2243
#define FMT_THROW(x)
Definition format.h:96
FMT_CONSTEXPR auto write(OutputIt out, Char value, const basic_format_specs< Char > &specs, locale_ref loc={}) -> OutputIt
Definition format.h:1338
not_this_one end(...)
Definition args.h:19
SPDLOG_INLINE std::shared_ptr< logger > get(const std::string &name)
Definition spdlog-inl.h:20
T size(T... args)
T strtod(T... args)
Definition format.h:897
FMT_CONSTEXPR auto format(const std::error_code &ec, FormatContext &ctx) const -> decltype(ctx.out())
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin())
T system_category(T... args)
T system(T... args)