os.h 15 KB

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