Skip to content

Commit b78b361

Browse files
committed
Use function overloading to handle variations in strerror_r() implementation.
Avoids using macros or cmake to detect implementation. Inspired by http://zverovich.net/2015/03/13/reliable-detection-of-strerror-variants.html. Signed-off-by: John Coyle <dx9err@gmail.com>
1 parent 57f685f commit b78b361

File tree

1 file changed

+16
-21
lines changed

1 file changed

+16
-21
lines changed

evpp/sockets.cc

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ namespace evpp {
88

99
static const std::string empty_string;
1010

11-
std::string strerror(int e) {
1211
#ifdef H_OS_WINDOWS
12+
std::string strerror(int e) {
1313
LPVOID buf = nullptr;
1414
::FormatMessageA(
1515
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
@@ -20,29 +20,24 @@ std::string strerror(int e) {
2020
LocalFree(buf);
2121
return s;
2222
}
23-
24-
#elif defined(H_OS_MACOSX)
25-
char buf[2048] = {};
26-
int rc = strerror_r(e, buf, sizeof(buf) - 1); // XSI-compliant
27-
if (rc == 0) {
28-
return std::string(buf);
29-
}
23+
return empty_string;
24+
}
3025
#else
26+
std::string handle_strerror_r(const char* s, const char* buf) // GNU-specific
27+
{
28+
return (s) ? std::string(s) : empty_string;
29+
}
30+
31+
std::string handle_strerror_r(int rc, const char* buf) // XSI-compliant
32+
{
33+
return (rc == 0) ? std::string(buf) : empty_string;
34+
}
35+
36+
std::string strerror(int e) {
3137
char buf[2048] = {};
32-
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
33-
int rc = strerror_r(e, buf, sizeof(buf) - 1); // XSI-compliant
34-
if (rc == 0) {
35-
return std::string(buf);
36-
}
37-
#else
38-
const char* s = strerror_r(e, buf, sizeof(buf) - 1); // GNU-specific
39-
if (s) {
40-
return std::string(s);
41-
}
42-
#endif
43-
#endif
44-
return empty_string;
38+
return handle_strerror_r(strerror_r(e, buf, sizeof(buf) - 1), buf);
4539
}
40+
#endif
4641

4742
namespace sock {
4843
evpp_socket_t CreateNonblockingSocket() {

0 commit comments

Comments
 (0)