os.h 15 KB

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