Debian Codegraph @

podofo/3rdparty/fmtlib/fmt/os.h

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