From 532348dcd376dc48985f06074c20b83e71940c25 Mon Sep 17 00:00:00 2001 From: Wouter ibens Date: Tue, 27 Aug 2024 21:37:19 +0200 Subject: [PATCH 1/2] Add available() function to subscriber --- src/sw/redis++/connection.cpp | 24 ++++++++++++++++++++++++ src/sw/redis++/connection.h | 2 ++ src/sw/redis++/subscriber.cpp | 6 ++++++ src/sw/redis++/subscriber.h | 2 ++ 4 files changed, 34 insertions(+) diff --git a/src/sw/redis++/connection.cpp b/src/sw/redis++/connection.cpp index 8a58f5c..c7fd1cf 100644 --- a/src/sw/redis++/connection.cpp +++ b/src/sw/redis++/connection.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "sw/redis++/reply.h" #include "sw/redis++/command.h" #include "sw/redis++/command_args.h" @@ -253,6 +254,29 @@ ReplyUPtr Connection::recv(bool handle_error_reply) { return reply; } +bool Connection::avail() { + auto *ctx = _context(); + + assert(ctx != nullptr); + + auto fd = ctx->fd; + + struct pollfd pfd; + pfd.fd = fd; + pfd.events = POLLIN; // Check for readability + + int result = poll(&pfd, 1, 0); // Timeout set to 0 milliseconds + if (result > 0 && (pfd.revents & POLLIN)) { + return true; + } else if (result == 0) { + return false; + } else { + // An error occurred + throw_error(*ctx, strerror(errno)); + return -1; + } +} + #ifdef REDIS_PLUS_PLUS_RESP_VERSION_3 void Connection::set_push_callback(redisPushFn *push_func) { diff --git a/src/sw/redis++/connection.h b/src/sw/redis++/connection.h index 9baf75e..06115a3 100644 --- a/src/sw/redis++/connection.h +++ b/src/sw/redis++/connection.h @@ -145,6 +145,8 @@ class Connection { ReplyUPtr recv(bool handle_error_reply = true); + bool avail(); + const ConnectionOptions& options() const { return _opts; } diff --git a/src/sw/redis++/subscriber.cpp b/src/sw/redis++/subscriber.cpp index f6f5612..35906f4 100644 --- a/src/sw/redis++/subscriber.cpp +++ b/src/sw/redis++/subscriber.cpp @@ -127,6 +127,12 @@ void Subscriber::consume() { } } +bool Subscriber::available() { + _check_connection(); + + return _connection.avail(); +} + Subscriber::MsgType Subscriber::_msg_type(redisReply *reply) const { if (reply == nullptr) { throw ProtoError("Null type reply."); diff --git a/src/sw/redis++/subscriber.h b/src/sw/redis++/subscriber.h index c8b8d78..8a50378 100644 --- a/src/sw/redis++/subscriber.h +++ b/src/sw/redis++/subscriber.h @@ -163,6 +163,8 @@ class Subscriber { void consume(); + bool available(); + private: friend class Redis; From 6fa79d4a7a9aca65bfbf90ad0e8ed17385483933 Mon Sep 17 00:00:00 2001 From: Wouter ibens Date: Tue, 27 Aug 2024 21:49:23 +0200 Subject: [PATCH 2/2] Remove unused return --- src/sw/redis++/connection.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/sw/redis++/connection.cpp b/src/sw/redis++/connection.cpp index c7fd1cf..d433ffc 100644 --- a/src/sw/redis++/connection.cpp +++ b/src/sw/redis++/connection.cpp @@ -273,7 +273,6 @@ bool Connection::avail() { } else { // An error occurred throw_error(*ctx, strerror(errno)); - return -1; } }