net/SocketDescriptor: move code to Receive(), Send()

This commit is contained in:
Max Kellermann 2023-09-27 09:52:49 +02:00 committed by Max Kellermann
parent 09a2da89a2
commit 8ca6606323
2 changed files with 35 additions and 13 deletions

View File

@ -403,6 +403,22 @@ SocketDescriptor::GetPeerAddress() const noexcept
return result;
}
ssize_t
SocketDescriptor::Receive(std::span<std::byte> dest, int flags) const noexcept
{
return ::recv(Get(), (char *)dest.data(), dest.size(), flags);
}
ssize_t
SocketDescriptor::Send(std::span<const std::byte> src, int flags) const noexcept
{
#ifdef __linux__
flags |= MSG_NOSIGNAL;
#endif
return ::send(Get(), (const char *)src.data(), src.size(), flags);
}
ssize_t
SocketDescriptor::Read(void *buffer, std::size_t length) const noexcept
{
@ -411,18 +427,7 @@ SocketDescriptor::Read(void *buffer, std::size_t length) const noexcept
flags |= MSG_DONTWAIT;
#endif
return ::recv(Get(), (char *)buffer, length, flags);
}
ssize_t
SocketDescriptor::Write(const void *buffer, std::size_t length) const noexcept
{
int flags = 0;
#ifdef __linux__
flags |= MSG_NOSIGNAL;
#endif
return ::send(Get(), (const char *)buffer, length, flags);
return Receive({static_cast<std::byte *>(buffer), length}, flags);
}
#ifdef _WIN32

View File

@ -10,6 +10,8 @@
#include "io/FileDescriptor.hxx"
#endif
#include <cstddef>
#include <span>
#include <type_traits>
#include <utility>
@ -260,8 +262,23 @@ public:
[[gnu::pure]]
StaticSocketAddress GetPeerAddress() const noexcept;
/**
* Wrapper for recv().
*/
ssize_t Receive(std::span<std::byte> dest, int flags=0) const noexcept;
/**
* Wrapper for send().
*
* MSG_NOSIGNAL is implicitly added (if available).
*/
ssize_t Send(std::span<const std::byte> src, int flags=0) const noexcept;
ssize_t Read(void *buffer, std::size_t length) const noexcept;
ssize_t Write(const void *buffer, std::size_t length) const noexcept;
ssize_t Write(const void *buffer, std::size_t length) const noexcept {
return Send({static_cast<const std::byte *>(buffer), length});
}
#ifdef _WIN32
int WaitReadable(int timeout_ms) const noexcept;