Commit 5bb2d64d authored by Max Kellermann's avatar Max Kellermann

SocketError: merge duplicate FormatMessage() calls

Make a class that contains the formatting code and the buffer.
parent bc66dc45
...@@ -87,27 +87,49 @@ IsSocketErrorClosed(socket_error_t code) ...@@ -87,27 +87,49 @@ IsSocketErrorClosed(socket_error_t code)
#endif #endif
} }
static inline void /**
SetSocketError(GError **error_r, socket_error_t code) * Helper class that formats a socket error message into a
{ * human-readable string. On Windows, a buffer is necessary for this,
* and this class hosts the buffer.
*/
class SocketErrorMessage {
#ifdef WIN32 #ifdef WIN32
if (error_r == NULL) char msg[256];
return; #else
const char *const msg;
#endif
char buffer[256]; public:
#ifdef WIN32
explicit SocketErrorMessage(socket_error_t code=GetSocketError()) {
DWORD nbytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | DWORD nbytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK, FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, code, 0, NULL, code, 0,
(LPSTR)buffer, sizeof(buffer), NULL); (LPSTR)msg, sizeof(msg), NULL);
const char *msg = nbytes > 0 if (nbytes == 0)
? buffer strcpy(msg, "Unknown error");
: "Unknown error"; }
g_set_error_literal(error_r, SocketErrorQuark(), code, msg);
#else #else
g_set_error_literal(error_r, SocketErrorQuark(), code, explicit SocketErrorMessage(socket_error_t code=GetSocketError())
g_strerror(code)); :msg(g_strerror(code)) {}
#endif #endif
operator const char *() const {
return msg;
}
};
static inline void
SetSocketError(GError **error_r, socket_error_t code)
{
#ifdef WIN32
if (error_r == NULL)
return;
#endif
const SocketErrorMessage msg(code);
g_set_error_literal(error_r, SocketErrorQuark(), code, msg);
} }
static inline void static inline void
...@@ -120,20 +142,8 @@ gcc_malloc ...@@ -120,20 +142,8 @@ gcc_malloc
static inline GError * static inline GError *
NewSocketError(socket_error_t code) NewSocketError(socket_error_t code)
{ {
#ifdef WIN32 const SocketErrorMessage msg(code);
char buffer[256];
DWORD nbytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, code, 0,
(LPSTR)buffer, sizeof(buffer), NULL);
const char *msg = nbytes > 0
? buffer
: "Unknown error";
return g_error_new_literal(SocketErrorQuark(), code, msg); return g_error_new_literal(SocketErrorQuark(), code, msg);
#else
return g_error_new_literal(SocketErrorQuark(), code, g_strerror(code));
#endif
} }
gcc_malloc gcc_malloc
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment