Changeset - r25686:fb6d0e17cffc
[Not reviewed]
master
0 2 0
rubidium42 - 3 years ago 2021-06-13 19:41:07
rubidium@openttd.org
Codechange: [Network] Let NetworkError return its std::string instead of a C-string
2 files changed with 3 insertions and 3 deletions:
0 comments (0 inline, 0 general)
src/network/core/os_abstraction.cpp
Show inline comments
 
@@ -67,46 +67,46 @@ bool NetworkError::IsConnectInProgress()
 
{
 
#if defined(_WIN32)
 
	return this->error == WSAEWOULDBLOCK;
 
#else
 
	return this->error == EINPROGRESS;
 
#endif
 
}
 

	
 
/**
 
 * Get the string representation of the error message.
 
 * @return The string representation that will get overwritten by next calls.
 
 */
 
const char *NetworkError::AsString() const
 
const std::string &NetworkError::AsString() const
 
{
 
	if (this->message.empty()) {
 
#if defined(_WIN32)
 
		char buffer[512];
 
		if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, this->error,
 
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, sizeof(buffer), NULL) == 0) {
 
			seprintf(buffer, lastof(buffer), "Unknown error %d", this->error);
 
		}
 
		this->message.assign(buffer);
 
#else
 
		/* Make strerror thread safe by locking access to it. There is a thread safe strerror_r, however
 
		 * the non-POSIX variant is available due to defining _GNU_SOURCE meaning it is not portable.
 
		 * The problem with the non-POSIX variant is that it does not necessarily fill the buffer with
 
		 * the error message but can also return a pointer to a static bit of memory, whereas the POSIX
 
		 * variant always fills the buffer. This makes the behaviour too erratic to work with. */
 
		static std::mutex mutex;
 
		std::lock_guard<std::mutex> guard(mutex);
 
		this->message.assign(strerror(this->error));
 
#endif
 
	}
 
	return this->message.c_str();
 
	return this->message;
 
}
 

	
 
/**
 
 * Check whether an error was actually set.
 
 * @return True iff an error was set.
 
 */
 
bool NetworkError::HasError() const
 
{
 
	return this->error != 0;
 
}
 

	
 
/**
src/network/core/os_abstraction.h
Show inline comments
 
@@ -20,25 +20,25 @@
 
 */
 
class NetworkError {
 
private:
 
	int error;                   ///< The underlying error number from errno or WSAGetLastError.
 
	mutable std::string message; ///< The string representation of the error (set on first call to #AsString).
 
public:
 
	NetworkError(int error);
 

	
 
	bool HasError() const;
 
	bool WouldBlock() const;
 
	bool IsConnectionReset() const;
 
	bool IsConnectInProgress() const;
 
	const char *AsString() const;
 
	const std::string &AsString() const;
 

	
 
	static NetworkError GetLast();
 
};
 

	
 
/* Include standard stuff per OS */
 

	
 
/* Windows stuff */
 
#if defined(_WIN32)
 
#include <errno.h>
 
#include <winsock2.h>
 
#include <ws2tcpip.h>
 
#include <windows.h>
0 comments (0 inline, 0 general)