| 71 | FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); |
| 72 | |
| 73 | class dispatcher { |
| 74 | private: |
| 75 | int error_code_; |
| 76 | char*& buffer_; |
| 77 | std::size_t buffer_size_; |
| 78 | |
| 79 | // A noop assignment operator to avoid bogus warnings. |
| 80 | void operator=(const dispatcher&) {} |
| 81 | |
| 82 | // Handle the result of XSI-compliant version of strerror_r. |
| 83 | int handle(int result) { |
| 84 | // glibc versions before 2.13 return result in errno. |
| 85 | return result == -1 ? errno : result; |
| 86 | } |
| 87 | |
| 88 | // Handle the result of GNU-specific version of strerror_r. |
| 89 | FMT_MAYBE_UNUSED |
| 90 | int handle(char* message) { |
| 91 | // If the buffer is full then the message is probably truncated. |
| 92 | if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) |
| 93 | return ERANGE; |
| 94 | buffer_ = message; |
| 95 | return 0; |
| 96 | } |
| 97 | |
| 98 | // Handle the case when strerror_r is not available. |
| 99 | FMT_MAYBE_UNUSED |
| 100 | int handle(internal::null<>) { |
| 101 | return fallback(strerror_s(buffer_, buffer_size_, error_code_)); |
| 102 | } |
| 103 | |
| 104 | // Fallback to strerror_s when strerror_r is not available. |
| 105 | FMT_MAYBE_UNUSED |
| 106 | int fallback(int result) { |
| 107 | // If the buffer is full then the message is probably truncated. |
| 108 | return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE |
| 109 | : result; |
| 110 | } |
| 111 | |
| 112 | #if !FMT_MSC_VER |
| 113 | // Fallback to strerror if strerror_r and strerror_s are not available. |
| 114 | int fallback(internal::null<>) { |
| 115 | errno = 0; |
| 116 | buffer_ = strerror(error_code_); |
| 117 | return errno; |
| 118 | } |
| 119 | #endif |
| 120 | |
| 121 | public: |
| 122 | dispatcher(int err_code, char*& buf, std::size_t buf_size) |
| 123 | : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} |
| 124 | |
| 125 | int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } |
| 126 | }; |
| 127 | return dispatcher(error_code, buffer, buffer_size).run(); |
| 128 | } |
| 129 | |