Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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