From 69e9ea2ac32a4490db7b2a30e72b91dffa2a5bd8 Mon Sep 17 00:00:00 2001 From: Francesco Date: Tue, 16 Sep 2025 22:25:59 +0200 Subject: [PATCH] feat(socket): add read/write all --- socket/mysocket.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ socket/mysocket.h | 4 ++++ 2 files changed, 51 insertions(+) diff --git a/socket/mysocket.c b/socket/mysocket.c index 0030ea1..245ccfe 100644 --- a/socket/mysocket.c +++ b/socket/mysocket.c @@ -35,3 +35,50 @@ int sock_platform_shutdown() { return 0; } + +int sock_readall(int socket, void *out, size_t n) { + char *p = (char *)out; + size_t bytes_to_read = n; + int bytes_read = 0; + + while (bytes_to_read > 0) { + bytes_read = recv(socket, p, bytes_to_read, 0); + + if (bytes_read > 0) { + p += bytes_read; + bytes_to_read -= bytes_read; + } else if (bytes_read == 0) { + break; + } else { + if (errno == EINTR) { + continue; + } + return -1; + } + } + + return n - bytes_to_read; +} + +int sock_writeall(int socket, const void *buf, size_t n) { + const char *p = (char *)buf; + size_t bytes_to_write = n; + int bytes_written; + + while (bytes_to_write > 0) { + bytes_written = send(socket, p, bytes_to_write, 0); + + if (bytes_written >= 0) { + p += bytes_written; + bytes_to_write -= bytes_written; + } else { + if (errno == EINTR) { + continue; + } + + return -1; + } + } + + return n; +} diff --git a/socket/mysocket.h b/socket/mysocket.h index b9ca7b8..c3c71ce 100644 --- a/socket/mysocket.h +++ b/socket/mysocket.h @@ -28,6 +28,10 @@ int sock_platform_init(); /* Use this to close a socket */ int sock_close(int socket); +/* Read/Write all to socket */ +int sock_readall(int socket, void *out, size_t n); +int sock_writeall(int socket, const void *buf, size_t n); + /* Use at exit */ int sock_platform_shutdown();