net: rename Sock::Reset() to Sock::Close() and make it private

Outside of `Sock`, `Sock::Reset()` was used in just one place (in
`i2p.cpp`) which can use the assignment operator instead.

This simplifies the public `Sock` API by having one method less.
This commit is contained in:
Vasil Dimov
2022-06-21 15:23:37 +02:00
parent e8ff3f0c52
commit a724c39606
7 changed files with 28 additions and 46 deletions

View File

@@ -39,11 +39,11 @@ Sock::Sock(Sock&& other)
other.m_socket = INVALID_SOCKET;
}
Sock::~Sock() { Reset(); }
Sock::~Sock() { Close(); }
Sock& Sock::operator=(Sock&& other)
{
Reset();
Close();
m_socket = other.m_socket;
other.m_socket = INVALID_SOCKET;
return *this;
@@ -51,21 +51,6 @@ Sock& Sock::operator=(Sock&& other)
SOCKET Sock::Get() const { return m_socket; }
void Sock::Reset() {
if (m_socket == INVALID_SOCKET) {
return;
}
#ifdef WIN32
int ret = closesocket(m_socket);
#else
int ret = close(m_socket);
#endif
if (ret) {
LogPrintf("Error closing socket %d: %s\n", m_socket, NetworkErrorString(WSAGetLastError()));
}
m_socket = INVALID_SOCKET;
}
ssize_t Sock::Send(const void* data, size_t len, int flags) const
{
return send(m_socket, static_cast<const char*>(data), len, flags);
@@ -372,6 +357,22 @@ bool Sock::IsConnected(std::string& errmsg) const
}
}
void Sock::Close()
{
if (m_socket == INVALID_SOCKET) {
return;
}
#ifdef WIN32
int ret = closesocket(m_socket);
#else
int ret = close(m_socket);
#endif
if (ret) {
LogPrintf("Error closing socket %d: %s\n", m_socket, NetworkErrorString(WSAGetLastError()));
}
m_socket = INVALID_SOCKET;
}
#ifdef WIN32
std::string NetworkErrorString(int err)
{

View File

@@ -68,11 +68,6 @@ public:
*/
[[nodiscard]] virtual SOCKET Get() const;
/**
* Close if non-empty.
*/
virtual void Reset();
/**
* send(2) wrapper. Equivalent to `send(this->Get(), data, len, flags);`. Code that uses this
* wrapper can be unit tested if this method is overridden by a mock Sock implementation.
@@ -245,6 +240,12 @@ protected:
* Contained socket. `INVALID_SOCKET` designates the object is empty.
*/
SOCKET m_socket;
private:
/**
* Close `m_socket` if it is not `INVALID_SOCKET`.
*/
void Close();
};
/** Return readable error string for a network error code */