From 8ca66063238690f3a43c1f46d0c15651cded1719 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Wed, 27 Sep 2023 09:52:49 +0200 Subject: [PATCH] net/SocketDescriptor: move code to Receive(), Send() --- src/net/SocketDescriptor.cxx | 29 +++++++++++++++++------------ src/net/SocketDescriptor.hxx | 19 ++++++++++++++++++- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/net/SocketDescriptor.cxx b/src/net/SocketDescriptor.cxx index 350931ea7..35f23a7f9 100644 --- a/src/net/SocketDescriptor.cxx +++ b/src/net/SocketDescriptor.cxx @@ -403,6 +403,22 @@ SocketDescriptor::GetPeerAddress() const noexcept return result; } +ssize_t +SocketDescriptor::Receive(std::span dest, int flags) const noexcept +{ + return ::recv(Get(), (char *)dest.data(), dest.size(), flags); +} + +ssize_t +SocketDescriptor::Send(std::span 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(buffer), length}, flags); } #ifdef _WIN32 diff --git a/src/net/SocketDescriptor.hxx b/src/net/SocketDescriptor.hxx index f333cd1ed..75f5983c8 100644 --- a/src/net/SocketDescriptor.hxx +++ b/src/net/SocketDescriptor.hxx @@ -10,6 +10,8 @@ #include "io/FileDescriptor.hxx" #endif +#include +#include #include #include @@ -260,8 +262,23 @@ public: [[gnu::pure]] StaticSocketAddress GetPeerAddress() const noexcept; + /** + * Wrapper for recv(). + */ + ssize_t Receive(std::span dest, int flags=0) const noexcept; + + /** + * Wrapper for send(). + * + * MSG_NOSIGNAL is implicitly added (if available). + */ + ssize_t Send(std::span 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(buffer), length}); + } #ifdef _WIN32 int WaitReadable(int timeout_ms) const noexcept;