From 60918c1f4ae38b0e6f2022b088e065b94564587c Mon Sep 17 00:00:00 2001 From: Mikhail Koviazin Date: Fri, 23 Aug 2024 14:24:14 +0200 Subject: [PATCH] format sources with current clang-format configuration Signed-off-by: Mikhail Koviazin --- examples/async-ae.c | 28 +- examples/async-glib.c | 25 +- examples/async-ivykis.c | 27 +- examples/async-libev.c | 27 +- examples/async-libevent-ssl.c | 30 +- examples/async-libevent.c | 27 +- examples/async-libhv.c | 29 +- examples/async-libsdevent.c | 28 +- examples/async-libuv.c | 30 +- examples/async-macosx.c | 26 +- examples/async-poll.c | 28 +- examples/async-qt.cpp | 17 +- examples/async-qt.h | 29 +- examples/async-valkeymoduleapi.c | 19 +- examples/blocking-push.c | 18 +- examples/blocking-ssl.c | 28 +- examples/blocking.c | 32 +- examples/cluster-async-tls.c | 8 +- examples/cluster-async.c | 10 +- examples/cluster-clientside-caching-async.c | 9 +- examples/cluster-simple.c | 3 +- examples/cluster-tls.c | 5 +- include/valkey/adapters/ae.h | 39 +- include/valkey/adapters/glib.h | 46 +- include/valkey/adapters/ivykis.h | 17 +- include/valkey/adapters/libev.h | 47 +- include/valkey/adapters/libevent.h | 20 +- include/valkey/adapters/libhv.h | 43 +- include/valkey/adapters/libsdevent.h | 28 +- include/valkey/adapters/libuv.h | 67 +- include/valkey/adapters/macosx.h | 70 +- include/valkey/adapters/poll.h | 28 +- include/valkey/adapters/qt.h | 134 +-- include/valkey/adapters/valkeymoduleapi.h | 35 +- include/valkey/alloc.h | 8 +- include/valkey/async.h | 12 +- include/valkey/dict.h | 52 +- include/valkey/read.h | 55 +- include/valkey/sds.h | 230 +++-- include/valkey/sockcompat.h | 17 +- include/valkey/valkey.h | 86 +- include/valkey/valkey_rdma.h | 14 +- include/valkey/valkey_ssl.h | 26 +- include/valkey/valkeycluster.h | 6 +- include/valkey/valkeycluster_ssl.h | 3 +- src/adlist.c | 5 +- src/alloc.c | 6 +- src/async.c | 209 ++-- src/async_private.h | 58 +- src/command.c | 19 +- src/command.h | 2 +- src/dict.c | 49 +- src/net.c | 138 +-- src/rdma.c | 47 +- src/read.c | 255 ++--- src/sds.c | 809 ++++++++------- src/sockcompat.c | 200 ++-- src/ssl.c | 130 +-- src/valkey.c | 276 ++--- src/valkey_private.h | 9 +- src/valkeycluster.c | 22 +- src/vkutil.c | 3 +- src/win32.h | 10 +- tests/client_test.c | 1012 ++++++++++--------- tests/clusterclient.c | 1 + tests/clusterclient_async.c | 1 + tests/clusterclient_reconnect_async.c | 1 + tests/ct_async.c | 1 + tests/ct_async_glib.c | 5 +- tests/ct_async_libev.c | 1 + tests/ct_async_libuv.c | 1 + tests/ct_commands.c | 1 + tests/ct_connection_ipv6.c | 1 + tests/ct_out_of_memory_handling.c | 11 +- tests/ct_specific_nodes.c | 10 +- tests/test_utils.c | 3 +- tests/test_utils.h | 84 +- tests/ut_parse_cmd.c | 10 +- 78 files changed, 2618 insertions(+), 2338 deletions(-) diff --git a/examples/async-ae.c b/examples/async-ae.c index ec4758f4..469de395 100644 --- a/examples/async-ae.c +++ b/examples/async-ae.c @@ -1,19 +1,21 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include /* Put event loop in the global scope, so it can be explicitly stopped */ static aeEventLoop *loop; void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -40,7 +42,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { aeStop(loop); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); valkeyAsyncContext *c = valkeyAsyncConnect("127.0.0.1", 6379); @@ -52,11 +54,11 @@ int main (int argc, char **argv) { loop = aeCreateEventLoop(64); valkeyAeAttach(loop, c); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); aeMain(loop); return 0; } - diff --git a/examples/async-glib.c b/examples/async-glib.c index 5137edc5..d4b3a934 100644 --- a/examples/async-glib.c +++ b/examples/async-glib.c @@ -1,15 +1,15 @@ -#include - -#include #include +#include + #include +#include + static GMainLoop *mainloop; static void -connect_cb (const valkeyAsyncContext *ac G_GNUC_UNUSED, - int status) -{ +connect_cb(const valkeyAsyncContext *ac G_GNUC_UNUSED, + int status) { if (status != VALKEY_OK) { g_printerr("Failed to connect: %s\n", ac->errstr); g_main_loop_quit(mainloop); @@ -19,9 +19,8 @@ connect_cb (const valkeyAsyncContext *ac G_GNUC_UNUSED, } static void -disconnect_cb (const valkeyAsyncContext *ac G_GNUC_UNUSED, - int status) -{ +disconnect_cb(const valkeyAsyncContext *ac G_GNUC_UNUSED, + int status) { if (status != VALKEY_OK) { g_error("Failed to disconnect: %s", ac->errstr); } else { @@ -33,8 +32,7 @@ disconnect_cb (const valkeyAsyncContext *ac G_GNUC_UNUSED, static void command_cb(valkeyAsyncContext *ac, gpointer r, - gpointer user_data G_GNUC_UNUSED) -{ + gpointer user_data G_GNUC_UNUSED) { valkeyReply *reply = r; if (reply) { @@ -44,10 +42,7 @@ command_cb(valkeyAsyncContext *ac, valkeyAsyncDisconnect(ac); } -gint -main (gint argc G_GNUC_UNUSED, - gchar *argv[] G_GNUC_UNUSED) -{ +gint main(gint argc G_GNUC_UNUSED, gchar *argv[] G_GNUC_UNUSED) { valkeyAsyncContext *ac; GMainContext *context = NULL; GSource *source; diff --git a/examples/async-ivykis.c b/examples/async-ivykis.c index a8c12892..97f485ff 100644 --- a/examples/async-ivykis.c +++ b/examples/async-ivykis.c @@ -1,16 +1,18 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -32,7 +34,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif @@ -47,10 +49,11 @@ int main (int argc, char **argv) { } valkeyIvykisAttach(c); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); iv_main(); diff --git a/examples/async-libev.c b/examples/async-libev.c index dcb2a378..31a49a05 100644 --- a/examples/async-libev.c +++ b/examples/async-libev.c @@ -1,16 +1,18 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -32,7 +34,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif @@ -45,10 +47,11 @@ int main (int argc, char **argv) { } valkeyLibevAttach(EV_DEFAULT_ c); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); ev_loop(EV_DEFAULT_ 0); return 0; } diff --git a/examples/async-libevent-ssl.c b/examples/async-libevent-ssl.c index 31ec5912..a2ee0f36 100644 --- a/examples/async-libevent-ssl.c +++ b/examples/async-libevent-ssl.c @@ -1,17 +1,19 @@ -#include -#include -#include -#include - +#include #include #include -#include + #include +#include +#include +#include +#include + void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -33,7 +35,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif @@ -61,7 +63,7 @@ int main (int argc, char **argv) { valkeyInitOpenSSL(); ssl = valkeyCreateSSLContext(caCert, NULL, - cert, certKey, NULL, &ssl_error); + cert, certKey, NULL, &ssl_error); if (!ssl) { printf("Error: %s\n", valkeySSLContextGetError(ssl_error)); return 1; @@ -78,11 +80,11 @@ int main (int argc, char **argv) { exit(1); } - valkeyLibeventAttach(c,base); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); + valkeyLibeventAttach(c, base); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); valkeyAsyncCommand(c, NULL, NULL, "SET key %b", value, nvalue); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); event_base_dispatch(base); valkeyFreeSSLContext(ssl); diff --git a/examples/async-libevent.c b/examples/async-libevent.c index 210443a8..c1f0d296 100644 --- a/examples/async-libevent.c +++ b/examples/async-libevent.c @@ -1,11 +1,12 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; @@ -15,7 +16,7 @@ void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { } return; } - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -37,7 +38,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif @@ -49,7 +50,6 @@ int main (int argc, char **argv) { tv.tv_sec = 1; options.connect_timeout = &tv; - valkeyAsyncContext *c = valkeyAsyncConnectWithOptions(&options); if (c->err) { /* Let *c leak for now... */ @@ -57,11 +57,12 @@ int main (int argc, char **argv) { return 1; } - valkeyLibeventAttach(c,base); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyLibeventAttach(c, base); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); event_base_dispatch(base); return 0; } diff --git a/examples/async-libhv.c b/examples/async-libhv.c index b70f96a3..44c1fbbc 100644 --- a/examples/async-libhv.c +++ b/examples/async-libhv.c @@ -1,16 +1,18 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -44,7 +46,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif @@ -56,13 +58,14 @@ int main (int argc, char **argv) { return 1; } - hloop_t* loop = hloop_new(HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS); + hloop_t *loop = hloop_new(HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS); valkeyLibhvAttach(c, loop); valkeyAsyncSetTimeout(c, (struct timeval){.tv_sec = 0, .tv_usec = 500000}); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); valkeyAsyncCommand(c, debugCallback, NULL, "DEBUG SLEEP %d", 1); hloop_run(loop); hloop_free(&loop); diff --git a/examples/async-libsdevent.c b/examples/async-libsdevent.c index 69a10e7c..becba71c 100644 --- a/examples/async-libsdevent.c +++ b/examples/async-libsdevent.c @@ -1,11 +1,12 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void debugCallback(valkeyAsyncContext *c, void *r, void *privdata) { (void)privdata; @@ -25,7 +26,7 @@ void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { printf("`GET key` error: %s\n", c->errstr ? c->errstr : "unknown error"); return; } - printf("`GET key` result: argv[%s]: %s\n", (char*)privdata, reply->str); + printf("`GET key` result: argv[%s]: %s\n", (char *)privdata, reply->str); /* start another request that demonstrate timeout */ valkeyAsyncCommand(c, debugCallback, NULL, "DEBUG SLEEP %f", 1.5); @@ -47,7 +48,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); struct sd_event *event; @@ -60,10 +61,10 @@ int main (int argc, char **argv) { return 1; } - valkeyLibsdeventAttach(c,event); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncSetTimeout(c, (struct timeval){ .tv_sec = 1, .tv_usec = 0}); + valkeyLibsdeventAttach(c, event); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncSetTimeout(c, (struct timeval){.tv_sec = 1, .tv_usec = 0}); /* In this demo, we first `set key`, then `get key` to demonstrate the basic usage of libsdevent adapter. @@ -72,8 +73,9 @@ int main (int argc, char **argv) { timeout error, which is shown in the `debugCallback`. */ - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); /* sd-event does not quit when there are no handlers registered. Manually exit after 1.5 seconds */ sd_event_source *s; diff --git a/examples/async-libuv.c b/examples/async-libuv.c index 7b356ec4..004f84ed 100644 --- a/examples/async-libuv.c +++ b/examples/async-libuv.c @@ -1,11 +1,12 @@ +#include +#include + +#include + +#include #include #include #include -#include - -#include -#include -#include void debugCallback(valkeyAsyncContext *c, void *r, void *privdata) { (void)privdata; //unused @@ -25,7 +26,7 @@ void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { printf("`GET key` error: %s\n", c->errstr ? c->errstr : "unknown error"); return; } - printf("`GET key` result: argv[%s]: %s\n", (char*)privdata, reply->str); + printf("`GET key` result: argv[%s]: %s\n", (char *)privdata, reply->str); /* start another request that demonstrate timeout */ valkeyAsyncCommand(c, debugCallback, NULL, "DEBUG SLEEP %f", 1.5); @@ -47,12 +48,12 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif - uv_loop_t* loop = uv_default_loop(); + uv_loop_t *loop = uv_default_loop(); valkeyAsyncContext *c = valkeyAsyncConnect("127.0.0.1", 6379); if (c->err) { @@ -61,10 +62,10 @@ int main (int argc, char **argv) { return 1; } - valkeyLibuvAttach(c,loop); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncSetTimeout(c, (struct timeval){ .tv_sec = 1, .tv_usec = 0}); + valkeyLibuvAttach(c, loop); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncSetTimeout(c, (struct timeval){.tv_sec = 1, .tv_usec = 0}); /* In this demo, we first `set key`, then `get key` to demonstrate the basic usage of libuv adapter. @@ -73,8 +74,9 @@ int main (int argc, char **argv) { timeout error, which is shown in the `debugCallback`. */ - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); uv_run(loop, UV_RUN_DEFAULT); return 0; diff --git a/examples/async-macosx.c b/examples/async-macosx.c index c8fb43bf..959a7ef2 100644 --- a/examples/async-macosx.c +++ b/examples/async-macosx.c @@ -31,16 +31,18 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include - -#include #include +#include + #include +#include + void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -63,11 +65,11 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); CFRunLoopRef loop = CFRunLoopGetCurrent(); - if( !loop ) { + if (!loop) { printf("Error: Cannot get current run loop\n"); return 1; } @@ -81,14 +83,14 @@ int main (int argc, char **argv) { valkeyMacOSAttach(c, loop); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); CFRunLoopRun(); return 0; } - diff --git a/examples/async-poll.c b/examples/async-poll.c index b39eaf4c..8fa1dd6f 100644 --- a/examples/async-poll.c +++ b/examples/async-poll.c @@ -1,19 +1,21 @@ +#include + +#include + +#include #include #include #include -#include #include -#include -#include - /* Put in the global scope, so that loop can be explicitly stopped */ static int exit_loop = 0; void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { valkeyReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + if (reply == NULL) + return; + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* Disconnect after receiving the reply to GET */ valkeyAsyncDisconnect(c); @@ -39,7 +41,7 @@ void disconnectCallback(const valkeyAsyncContext *c, int status) { printf("Disconnected...\n"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); valkeyAsyncContext *c = valkeyAsyncConnect("127.0.0.1", 6379); @@ -50,12 +52,12 @@ int main (int argc, char **argv) { } valkeyPollAttach(c); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); - while (!exit_loop) - { + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncCommand( + c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1])); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); + while (!exit_loop) { valkeyPollTick(c, 0.1); } return 0; diff --git a/examples/async-qt.cpp b/examples/async-qt.cpp index 1d99ccb6..8f1cbaca 100644 --- a/examples/async-qt.cpp +++ b/examples/async-qt.cpp @@ -1,16 +1,17 @@ #include using namespace std; +#include "async-qt.h" + #include #include -#include "async-qt.h" - -void getCallback(valkeyAsyncContext *, void * r, void * privdata) { +void getCallback(valkeyAsyncContext *, void *r, void *privdata) { - valkeyReply * reply = static_cast(r); - ExampleQt * ex = static_cast(privdata); - if (reply == nullptr || ex == nullptr) return; + valkeyReply *reply = static_cast(r); + ExampleQt *ex = static_cast(privdata); + if (reply == nullptr || ex == nullptr) + return; cout << "key: " << reply->str << endl; @@ -33,11 +34,11 @@ void ExampleQt::run() { valkeyAsyncCommand(m_ctx, getCallback, this, "GET key"); } -int main (int argc, char **argv) { +int main(int argc, char **argv) { QCoreApplication app(argc, argv); - ExampleQt example(argv[argc-1]); + ExampleQt example(argv[argc - 1]); QObject::connect(&example, SIGNAL(finished()), &app, SLOT(quit())); QTimer::singleShot(0, &example, SLOT(run())); diff --git a/examples/async-qt.h b/examples/async-qt.h index 851d66f6..254a30b1 100644 --- a/examples/async-qt.h +++ b/examples/async-qt.h @@ -7,26 +7,25 @@ class ExampleQt : public QObject { Q_OBJECT - public: - ExampleQt(const char * value, QObject * parent = 0) - : QObject(parent), m_value(value) {} + public: + ExampleQt(const char *value, QObject *parent = 0) + : QObject(parent), m_value(value) {} - signals: - void finished(); + signals: + void finished(); - public slots: - void run(); + public slots: + void run(); - private: - void finish() { emit finished(); } + private: + void finish() { emit finished(); } - private: - const char * m_value; - valkeyAsyncContext * m_ctx; - ValkeyQtAdapter m_adapter; + private: + const char *m_value; + valkeyAsyncContext *m_ctx; + ValkeyQtAdapter m_adapter; - friend - void getCallback(valkeyAsyncContext *, void *, void *); + friend void getCallback(valkeyAsyncContext *, void *, void *); }; #endif /* VALKEY_EXAMPLE_QT_H */ diff --git a/examples/async-valkeymoduleapi.c b/examples/async-valkeymoduleapi.c index bc52cbe4..cef491d8 100644 --- a/examples/async-valkeymoduleapi.c +++ b/examples/async-valkeymoduleapi.c @@ -1,11 +1,10 @@ +#include +#include +#include #include #include #include -#include - #include -#include -#include void debugCallback(valkeyAsyncContext *c, void *r, void *privdata) { (void)privdata; //unused @@ -27,7 +26,7 @@ void getCallback(valkeyAsyncContext *c, void *r, void *privdata) { } return; } - printf("argv[%s]: %s\n", (char*)privdata, reply->str); + printf("argv[%s]: %s\n", (char *)privdata, reply->str); /* start another request that demonstrate timeout */ valkeyAsyncCommand(c, debugCallback, NULL, "DEBUG SLEEP %f", 1.5); @@ -72,13 +71,13 @@ int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int arg } size_t len; - const char *val = ValkeyModule_StringPtrLen(argv[argc-1], &len); + const char *val = ValkeyModule_StringPtrLen(argv[argc - 1], &len); ValkeyModuleCtx *module_ctx = ValkeyModule_GetDetachedThreadSafeContext(ctx); valkeyModuleAttach(c, module_ctx); - valkeyAsyncSetConnectCallback(c,connectCallback); - valkeyAsyncSetDisconnectCallback(c,disconnectCallback); - valkeyAsyncSetTimeout(c, (struct timeval){ .tv_sec = 1, .tv_usec = 0}); + valkeyAsyncSetConnectCallback(c, connectCallback); + valkeyAsyncSetDisconnectCallback(c, disconnectCallback); + valkeyAsyncSetTimeout(c, (struct timeval){.tv_sec = 1, .tv_usec = 0}); /* In this demo, we first `set key`, then `get key` to demonstrate the basic usage of the adapter. @@ -88,6 +87,6 @@ int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int arg */ valkeyAsyncCommand(c, NULL, NULL, "SET key %b", val, len); - valkeyAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); + valkeyAsyncCommand(c, getCallback, (char *)"end-1", "GET key"); return 0; } diff --git a/examples/blocking-push.c b/examples/blocking-push.c index bf438d98..71bb169c 100644 --- a/examples/blocking-push.c +++ b/examples/blocking-push.c @@ -27,17 +27,20 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ +#include + #include #include #include -#include #define KEY_COUNT 5 -#define panicAbort(fmt, ...) \ - do { \ - fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, __VA_ARGS__); \ - exit(-1); \ +#define panicAbort(fmt, ...) \ + do { \ + fprintf( \ + stderr, \ + "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, __VA_ARGS__); \ + exit(-1); \ } while (0) static void assertReplyAndFree(valkeyContext *context, valkeyReply *reply, int type) { @@ -64,7 +67,7 @@ static void enableClientTracking(valkeyContext *c) { if (reply->type != VALKEY_REPLY_MAP) { fprintf(stderr, "Error: Can't send HELLO 3 command. Are you sure you're "); fprintf(stderr, "connected to valkey-server >= 6.0.0?\nServer error: %s\n", - reply->type == VALKEY_REPLY_ERROR ? reply->str : "(unknown)"); + reply->type == VALKEY_REPLY_ERROR ? reply->str : "(unknown)"); exit(-1); } @@ -82,8 +85,7 @@ void pushReplyHandler(void *privdata, void *r) { /* Sanity check on the invalidation reply */ if (reply->type != VALKEY_REPLY_PUSH || reply->elements != 2 || reply->element[1]->type != VALKEY_REPLY_ARRAY || - reply->element[1]->element[0]->type != VALKEY_REPLY_STRING) - { + reply->element[1]->element[0]->type != VALKEY_REPLY_STRING) { panicAbort("%s", "Can't parse PUSH message!"); } diff --git a/examples/blocking-ssl.c b/examples/blocking-ssl.c index 990d27c2..aaaafe94 100644 --- a/examples/blocking-ssl.c +++ b/examples/blocking-ssl.c @@ -1,10 +1,10 @@ +#include +#include + #include #include #include -#include -#include - #ifdef _MSC_VER #include /* For struct timeval */ #endif @@ -32,7 +32,7 @@ int main(int argc, char **argv) { exit(1); } - struct timeval tv = { 1, 500000 }; // 1.5 seconds + struct timeval tv = {1, 500000}; // 1.5 seconds valkeyOptions options = {0}; VALKEY_OPTIONS_SET_TCP(&options, hostname, port); options.connect_timeout = &tv; @@ -56,46 +56,46 @@ int main(int argc, char **argv) { } /* PING server */ - reply = valkeyCommand(c,"PING"); + reply = valkeyCommand(c, "PING"); printf("PING: %s\n", reply->str); freeReplyObject(reply); /* Set a key */ - reply = valkeyCommand(c,"SET %s %s", "foo", "hello world"); + reply = valkeyCommand(c, "SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* Set a key using binary safe API */ - reply = valkeyCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); + reply = valkeyCommand(c, "SET %b %b", "bar", (size_t)3, "hello", (size_t)5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* Try a GET and two INCR */ - reply = valkeyCommand(c,"GET foo"); + reply = valkeyCommand(c, "GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); - reply = valkeyCommand(c,"INCR counter"); + reply = valkeyCommand(c, "INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* again ... */ - reply = valkeyCommand(c,"INCR counter"); + reply = valkeyCommand(c, "INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* Create a list of numbers, from 0 to 9 */ - reply = valkeyCommand(c,"DEL mylist"); + reply = valkeyCommand(c, "DEL mylist"); freeReplyObject(reply); for (j = 0; j < 10; j++) { char buf[64]; - snprintf(buf,64,"%u",j); - reply = valkeyCommand(c,"LPUSH mylist element-%s", buf); + snprintf(buf, 64, "%u", j); + reply = valkeyCommand(c, "LPUSH mylist element-%s", buf); freeReplyObject(reply); } /* Let's check what we have inside the list */ - reply = valkeyCommand(c,"LRANGE mylist 0 -1"); + reply = valkeyCommand(c, "LRANGE mylist 0 -1"); if (reply->type == VALKEY_REPLY_ARRAY) { for (j = 0; j < reply->elements; j++) { printf("%u) %s\n", j, reply->element[j]->str); diff --git a/examples/blocking.c b/examples/blocking.c index ced05bb1..453f3e1f 100644 --- a/examples/blocking.c +++ b/examples/blocking.c @@ -1,7 +1,8 @@ +#include + #include #include #include -#include #ifdef _MSC_VER #include /* For struct timeval */ @@ -17,11 +18,11 @@ static void example_argv_command(valkeyContext *c, size_t n) { argvlen = malloc(sizeof(*argvlen) * (2 + n)); /* First the command */ - argv[0] = (char*)"RPUSH"; + argv[0] = (char *)"RPUSH"; argvlen[0] = sizeof("RPUSH") - 1; /* Now our key */ - argv[1] = (char*)"argvlist"; + argv[1] = (char *)"argvlist"; argvlen[1] = sizeof("argvlist") - 1; /* Now add the entries we wish to add to the list */ @@ -33,7 +34,8 @@ static void example_argv_command(valkeyContext *c, size_t n) { /* Execute the command using valkeyCommandArgv. We're sending the arguments with * two explicit arrays. One for each argument's string, and the other for its * length. */ - reply = valkeyCommandArgv(c, n + 2, (const char **)argv, (const size_t*)argvlen); + reply = valkeyCommandArgv( + c, n + 2, (const char **)argv, (const size_t *)argvlen); if (reply == NULL || c->err) { fprintf(stderr, "Error: Couldn't execute valkeyCommandArgv\n"); @@ -71,7 +73,7 @@ int main(int argc, char **argv) { int port = (argc > 2) ? atoi(argv[2]) : 6379; - struct timeval timeout = { 1, 500000 }; // 1.5 seconds + struct timeval timeout = {1, 500000}; // 1.5 seconds if (isunix) { c = valkeyConnectUnixWithTimeout(hostname, timeout); } else { @@ -88,46 +90,46 @@ int main(int argc, char **argv) { } /* PING server */ - reply = valkeyCommand(c,"PING"); + reply = valkeyCommand(c, "PING"); printf("PING: %s\n", reply->str); freeReplyObject(reply); /* Set a key */ - reply = valkeyCommand(c,"SET %s %s", "foo", "hello world"); + reply = valkeyCommand(c, "SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* Set a key using binary safe API */ - reply = valkeyCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); + reply = valkeyCommand(c, "SET %b %b", "bar", (size_t)3, "hello", (size_t)5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* Try a GET and two INCR */ - reply = valkeyCommand(c,"GET foo"); + reply = valkeyCommand(c, "GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); - reply = valkeyCommand(c,"INCR counter"); + reply = valkeyCommand(c, "INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* again ... */ - reply = valkeyCommand(c,"INCR counter"); + reply = valkeyCommand(c, "INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* Create a list of numbers, from 0 to 9 */ - reply = valkeyCommand(c,"DEL mylist"); + reply = valkeyCommand(c, "DEL mylist"); freeReplyObject(reply); for (j = 0; j < 10; j++) { char buf[64]; - snprintf(buf,64,"%u",j); - reply = valkeyCommand(c,"LPUSH mylist element-%s", buf); + snprintf(buf, 64, "%u", j); + reply = valkeyCommand(c, "LPUSH mylist element-%s", buf); freeReplyObject(reply); } /* Let's check what we have inside the list */ - reply = valkeyCommand(c,"LRANGE mylist 0 -1"); + reply = valkeyCommand(c, "LRANGE mylist 0 -1"); if (reply->type == VALKEY_REPLY_ARRAY) { for (j = 0; j < reply->elements; j++) { printf("%u) %s\n", j, reply->element[j]->str); diff --git a/examples/cluster-async-tls.c b/examples/cluster-async-tls.c index 8d1c04f9..1494dc4d 100644 --- a/examples/cluster-async-tls.c +++ b/examples/cluster-async-tls.c @@ -1,9 +1,11 @@ +#include +#include + +#include + #include #include #include -#include -#include -#include #define CLUSTER_NODE_TLS "127.0.0.1:7300" diff --git a/examples/cluster-async.c b/examples/cluster-async.c index b703be1b..5ec6b818 100644 --- a/examples/cluster-async.c +++ b/examples/cluster-async.c @@ -1,7 +1,9 @@ +#include + +#include + #include #include -#include -#include void getCallback(valkeyClusterAsyncContext *cc, void *r, void *privdata) { valkeyReply *reply = (valkeyReply *)r; @@ -45,8 +47,8 @@ void disconnectCallback(const valkeyAsyncContext *ac, int status) { } int main(int argc, char **argv) { - (void) argc; - (void) argv; + (void)argc; + (void)argv; printf("Connecting...\n"); valkeyClusterAsyncContext *cc = valkeyClusterAsyncConnect("127.0.0.1:7000", VALKEYCLUSTER_FLAG_NULL); diff --git a/examples/cluster-clientside-caching-async.c b/examples/cluster-clientside-caching-async.c index 50b29632..24c9fb34 100644 --- a/examples/cluster-clientside-caching-async.c +++ b/examples/cluster-clientside-caching-async.c @@ -4,9 +4,10 @@ * messages are received via the registered push callback. * The disconnect callback should also be used as an indication of invalidation. */ -#include #include +#include + #include #include #include @@ -83,7 +84,7 @@ void getCallback1(valkeyClusterAsyncContext *acc, void *r, void *privdata) { /* Push message callback handling invalidation messages. */ void pushCallback(valkeyAsyncContext *ac, void *r) { - (void) ac; + (void)ac; valkeyReply *reply = r; if (!(reply->type == VALKEY_REPLY_PUSH && reply->elements == 2 && reply->element[0]->type == VALKEY_REPLY_STRING && @@ -140,8 +141,8 @@ void modifyKey(const char *key, const char *value) { } int main(int argc, char **argv) { - (void) argc; - (void) argv; + (void)argc; + (void)argv; valkeyClusterAsyncContext *acc = valkeyClusterAsyncContextInit(); assert(acc); diff --git a/examples/cluster-simple.c b/examples/cluster-simple.c index a14f458c..60166837 100644 --- a/examples/cluster-simple.c +++ b/examples/cluster-simple.c @@ -1,6 +1,7 @@ +#include + #include #include -#include int main(int argc, char **argv) { UNUSED(argc); diff --git a/examples/cluster-tls.c b/examples/cluster-tls.c index 8ce9a98b..86d69be3 100644 --- a/examples/cluster-tls.c +++ b/examples/cluster-tls.c @@ -1,10 +1,11 @@ -#include -#include #include #include #include #include +#include +#include + #define CLUSTER_NODE_TLS "127.0.0.1:7301" int main(int argc, char **argv) { diff --git a/include/valkey/adapters/ae.h b/include/valkey/adapters/ae.h index db1ec882..9061a28b 100644 --- a/include/valkey/adapters/ae.h +++ b/include/valkey/adapters/ae.h @@ -30,12 +30,13 @@ #ifndef VALKEY_AE_H #define VALKEY_AE_H -#include -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" #include "../valkeycluster.h" +#include +#include + typedef struct valkeyAeEvents { valkeyAsyncContext *context; aeEventLoop *loop; @@ -44,57 +45,61 @@ typedef struct valkeyAeEvents { } valkeyAeEvents; static void valkeyAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) { - ((void)el); ((void)fd); ((void)mask); + ((void)el); + ((void)fd); + ((void)mask); - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; valkeyAsyncHandleRead(e->context); } static void valkeyAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) { - ((void)el); ((void)fd); ((void)mask); + ((void)el); + ((void)fd); + ((void)mask); - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; valkeyAsyncHandleWrite(e->context); } static void valkeyAeAddRead(void *privdata) { - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; aeEventLoop *loop = e->loop; if (!e->reading) { e->reading = 1; - aeCreateFileEvent(loop,e->fd,AE_READABLE,valkeyAeReadEvent,e); + aeCreateFileEvent(loop, e->fd, AE_READABLE, valkeyAeReadEvent, e); } } static void valkeyAeDelRead(void *privdata) { - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; aeEventLoop *loop = e->loop; if (e->reading) { e->reading = 0; - aeDeleteFileEvent(loop,e->fd,AE_READABLE); + aeDeleteFileEvent(loop, e->fd, AE_READABLE); } } static void valkeyAeAddWrite(void *privdata) { - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; aeEventLoop *loop = e->loop; if (!e->writing) { e->writing = 1; - aeCreateFileEvent(loop,e->fd,AE_WRITABLE,valkeyAeWriteEvent,e); + aeCreateFileEvent(loop, e->fd, AE_WRITABLE, valkeyAeWriteEvent, e); } } static void valkeyAeDelWrite(void *privdata) { - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; aeEventLoop *loop = e->loop; if (e->writing) { e->writing = 0; - aeDeleteFileEvent(loop,e->fd,AE_WRITABLE); + aeDeleteFileEvent(loop, e->fd, AE_WRITABLE); } } static void valkeyAeCleanup(void *privdata) { - valkeyAeEvents *e = (valkeyAeEvents*)privdata; + valkeyAeEvents *e = (valkeyAeEvents *)privdata; valkeyAeDelRead(privdata); valkeyAeDelWrite(privdata); vk_free(e); @@ -109,7 +114,7 @@ static int valkeyAeAttach(aeEventLoop *loop, valkeyAsyncContext *ac) { return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyAeEvents*)vk_malloc(sizeof(*e)); + e = (valkeyAeEvents *)vk_malloc(sizeof(*e)); if (e == NULL) return VALKEY_ERR; diff --git a/include/valkey/adapters/glib.h b/include/valkey/adapters/glib.h index c7b2ab62..22383799 100644 --- a/include/valkey/adapters/glib.h +++ b/include/valkey/adapters/glib.h @@ -1,12 +1,12 @@ #ifndef VALKEY_GLIB_H #define VALKEY_GLIB_H -#include - -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" #include "../valkeycluster.h" +#include + typedef struct { GSource source; @@ -15,8 +15,7 @@ typedef struct } ValkeySource; static void -valkey_source_add_read (gpointer data) -{ +valkey_source_add_read(gpointer data) { ValkeySource *source = (ValkeySource *)data; g_return_if_fail(source); source->poll_fd.events |= G_IO_IN; @@ -24,8 +23,7 @@ valkey_source_add_read (gpointer data) } static void -valkey_source_del_read (gpointer data) -{ +valkey_source_del_read(gpointer data) { ValkeySource *source = (ValkeySource *)data; g_return_if_fail(source); source->poll_fd.events &= ~G_IO_IN; @@ -33,8 +31,7 @@ valkey_source_del_read (gpointer data) } static void -valkey_source_add_write (gpointer data) -{ +valkey_source_add_write(gpointer data) { ValkeySource *source = (ValkeySource *)data; g_return_if_fail(source); source->poll_fd.events |= G_IO_OUT; @@ -42,8 +39,7 @@ valkey_source_add_write (gpointer data) } static void -valkey_source_del_write (gpointer data) -{ +valkey_source_del_write(gpointer data) { ValkeySource *source = (ValkeySource *)data; g_return_if_fail(source); source->poll_fd.events &= ~G_IO_OUT; @@ -51,8 +47,7 @@ valkey_source_del_write (gpointer data) } static void -valkey_source_cleanup (gpointer data) -{ +valkey_source_cleanup(gpointer data) { ValkeySource *source = (ValkeySource *)data; g_return_if_fail(source); @@ -70,26 +65,23 @@ valkey_source_cleanup (gpointer data) } static gboolean -valkey_source_prepare (GSource *source, - gint *timeout_) -{ +valkey_source_prepare(GSource *source, + gint *timeout_) { ValkeySource *valkey = (ValkeySource *)source; *timeout_ = -1; return !!(valkey->poll_fd.events & valkey->poll_fd.revents); } static gboolean -valkey_source_check (GSource *source) -{ +valkey_source_check(GSource *source) { ValkeySource *valkey = (ValkeySource *)source; return !!(valkey->poll_fd.events & valkey->poll_fd.revents); } static gboolean -valkey_source_dispatch (GSource *source, - GSourceFunc callback, - gpointer user_data) -{ +valkey_source_dispatch(GSource *source, + GSourceFunc callback, + gpointer user_data) { ValkeySource *valkey = (ValkeySource *)source; if ((valkey->poll_fd.revents & G_IO_OUT)) { @@ -110,8 +102,7 @@ valkey_source_dispatch (GSource *source, } static void -valkey_source_finalize (GSource *source) -{ +valkey_source_finalize(GSource *source) { ValkeySource *valkey = (ValkeySource *)source; if (valkey->poll_fd.fd >= 0) { @@ -121,11 +112,10 @@ valkey_source_finalize (GSource *source) } static GSource * -valkey_source_new (valkeyAsyncContext *ac) -{ +valkey_source_new(valkeyAsyncContext *ac) { static GSourceFuncs source_funcs = { - .prepare = valkey_source_prepare, - .check = valkey_source_check, + .prepare = valkey_source_prepare, + .check = valkey_source_check, .dispatch = valkey_source_dispatch, .finalize = valkey_source_finalize, }; diff --git a/include/valkey/adapters/ivykis.h b/include/valkey/adapters/ivykis.h index fd5a0f24..f5d2a871 100644 --- a/include/valkey/adapters/ivykis.h +++ b/include/valkey/adapters/ivykis.h @@ -1,8 +1,9 @@ #ifndef VALKEY_IVYKIS_H #define VALKEY_IVYKIS_H -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" + +#include typedef struct valkeyIvykisEvents { valkeyAsyncContext *context; @@ -20,27 +21,27 @@ static void valkeyIvykisWriteEvent(void *arg) { } static void valkeyIvykisAddRead(void *privdata) { - valkeyIvykisEvents *e = (valkeyIvykisEvents*)privdata; + valkeyIvykisEvents *e = (valkeyIvykisEvents *)privdata; iv_fd_set_handler_in(&e->fd, valkeyIvykisReadEvent); } static void valkeyIvykisDelRead(void *privdata) { - valkeyIvykisEvents *e = (valkeyIvykisEvents*)privdata; + valkeyIvykisEvents *e = (valkeyIvykisEvents *)privdata; iv_fd_set_handler_in(&e->fd, NULL); } static void valkeyIvykisAddWrite(void *privdata) { - valkeyIvykisEvents *e = (valkeyIvykisEvents*)privdata; + valkeyIvykisEvents *e = (valkeyIvykisEvents *)privdata; iv_fd_set_handler_out(&e->fd, valkeyIvykisWriteEvent); } static void valkeyIvykisDelWrite(void *privdata) { - valkeyIvykisEvents *e = (valkeyIvykisEvents*)privdata; + valkeyIvykisEvents *e = (valkeyIvykisEvents *)privdata; iv_fd_set_handler_out(&e->fd, NULL); } static void valkeyIvykisCleanup(void *privdata) { - valkeyIvykisEvents *e = (valkeyIvykisEvents*)privdata; + valkeyIvykisEvents *e = (valkeyIvykisEvents *)privdata; iv_fd_unregister(&e->fd); vk_free(e); @@ -55,7 +56,7 @@ static int valkeyIvykisAttach(valkeyAsyncContext *ac) { return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyIvykisEvents*)vk_malloc(sizeof(*e)); + e = (valkeyIvykisEvents *)vk_malloc(sizeof(*e)); if (e == NULL) return VALKEY_ERR; diff --git a/include/valkey/adapters/libev.h b/include/valkey/adapters/libev.h index dc6670ac..d8b206b1 100644 --- a/include/valkey/adapters/libev.h +++ b/include/valkey/adapters/libev.h @@ -30,13 +30,14 @@ #ifndef VALKEY_LIBEV_H #define VALKEY_LIBEV_H -#include -#include -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" #include "../valkeycluster.h" +#include +#include +#include + typedef struct valkeyLibevEvents { valkeyAsyncContext *context; struct ev_loop *loop; @@ -51,7 +52,7 @@ static void valkeyLibevReadEvent(EV_P_ ev_io *watcher, int revents) { #endif ((void)revents); - valkeyLibevEvents *e = (valkeyLibevEvents*)watcher->data; + valkeyLibevEvents *e = (valkeyLibevEvents *)watcher->data; valkeyAsyncHandleRead(e->context); } @@ -61,64 +62,64 @@ static void valkeyLibevWriteEvent(EV_P_ ev_io *watcher, int revents) { #endif ((void)revents); - valkeyLibevEvents *e = (valkeyLibevEvents*)watcher->data; + valkeyLibevEvents *e = (valkeyLibevEvents *)watcher->data; valkeyAsyncHandleWrite(e->context); } static void valkeyLibevAddRead(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif if (!e->reading) { e->reading = 1; - ev_io_start(EV_A_ &e->rev); + ev_io_start(EV_A_ & e->rev); } } static void valkeyLibevDelRead(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif if (e->reading) { e->reading = 0; - ev_io_stop(EV_A_ &e->rev); + ev_io_stop(EV_A_ & e->rev); } } static void valkeyLibevAddWrite(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif if (!e->writing) { e->writing = 1; - ev_io_start(EV_A_ &e->wev); + ev_io_start(EV_A_ & e->wev); } } static void valkeyLibevDelWrite(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif if (e->writing) { e->writing = 0; - ev_io_stop(EV_A_ &e->wev); + ev_io_stop(EV_A_ & e->wev); } } static void valkeyLibevStopTimer(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif - ev_timer_stop(EV_A_ &e->timer); + ev_timer_stop(EV_A_ & e->timer); } static void valkeyLibevCleanup(void *privdata) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; valkeyLibevDelRead(privdata); valkeyLibevDelWrite(privdata); valkeyLibevStopTimer(privdata); @@ -130,12 +131,12 @@ static void valkeyLibevTimeout(EV_P_ ev_timer *timer, int revents) { ((void)EV_A); #endif ((void)revents); - valkeyLibevEvents *e = (valkeyLibevEvents*)timer->data; + valkeyLibevEvents *e = (valkeyLibevEvents *)timer->data; valkeyAsyncHandleTimeout(e->context); } static void valkeyLibevSetTimeout(void *privdata, struct timeval tv) { - valkeyLibevEvents *e = (valkeyLibevEvents*)privdata; + valkeyLibevEvents *e = (valkeyLibevEvents *)privdata; #if EV_MULTIPLICITY struct ev_loop *loop = e->loop; #endif @@ -146,7 +147,7 @@ static void valkeyLibevSetTimeout(void *privdata, struct timeval tv) { } e->timer.repeat = tv.tv_sec + tv.tv_usec / 1000000.00; - ev_timer_again(EV_A_ &e->timer); + ev_timer_again(EV_A_ & e->timer); } static int valkeyLibevAttach(EV_P_ valkeyAsyncContext *ac) { @@ -158,7 +159,7 @@ static int valkeyLibevAttach(EV_P_ valkeyAsyncContext *ac) { return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyLibevEvents*)vk_calloc(1, sizeof(*e)); + e = (valkeyLibevEvents *)vk_calloc(1, sizeof(*e)); if (e == NULL) return VALKEY_ERR; @@ -181,8 +182,8 @@ static int valkeyLibevAttach(EV_P_ valkeyAsyncContext *ac) { ac->ev.data = e; /* Initialize read/write events */ - ev_io_init(&e->rev,valkeyLibevReadEvent,c->fd,EV_READ); - ev_io_init(&e->wev,valkeyLibevWriteEvent,c->fd,EV_WRITE); + ev_io_init(&e->rev, valkeyLibevReadEvent, c->fd, EV_READ); + ev_io_init(&e->wev, valkeyLibevWriteEvent, c->fd, EV_WRITE); return VALKEY_OK; } diff --git a/include/valkey/adapters/libevent.h b/include/valkey/adapters/libevent.h index 8350bec0..68f20f06 100644 --- a/include/valkey/adapters/libevent.h +++ b/include/valkey/adapters/libevent.h @@ -30,11 +30,12 @@ #ifndef VALKEY_LIBEVENT_H #define VALKEY_LIBEVENT_H -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" #include "../valkeycluster.h" +#include + #define VALKEY_LIBEVENT_DELETED 0x01 #define VALKEY_LIBEVENT_ENTERED 0x02 @@ -53,12 +54,13 @@ static void valkeyLibeventDestroy(valkeyLibeventEvents *e) { static void valkeyLibeventHandler(evutil_socket_t fd, short event, void *arg) { ((void)fd); - valkeyLibeventEvents *e = (valkeyLibeventEvents*)arg; + valkeyLibeventEvents *e = (valkeyLibeventEvents *)arg; e->state |= VALKEY_LIBEVENT_ENTERED; - #define CHECK_DELETED() if (e->state & VALKEY_LIBEVENT_DELETED) {\ - valkeyLibeventDestroy(e);\ - return; \ +#define CHECK_DELETED() \ + if (e->state & VALKEY_LIBEVENT_DELETED) { \ + valkeyLibeventDestroy(e); \ + return; \ } if ((event & EV_TIMEOUT) && (e->state & VALKEY_LIBEVENT_DELETED) == 0) { @@ -77,7 +79,7 @@ static void valkeyLibeventHandler(evutil_socket_t fd, short event, void *arg) { } e->state &= ~VALKEY_LIBEVENT_ENTERED; - #undef CHECK_DELETED +#undef CHECK_DELETED } static void valkeyLibeventUpdate(void *privdata, short flag, int isRemove) { @@ -121,7 +123,7 @@ static void valkeyLibeventDelWrite(void *privdata) { } static void valkeyLibeventCleanup(void *privdata) { - valkeyLibeventEvents *e = (valkeyLibeventEvents*)privdata; + valkeyLibeventEvents *e = (valkeyLibeventEvents *)privdata; if (!e) { return; } @@ -153,7 +155,7 @@ static int valkeyLibeventAttach(valkeyAsyncContext *ac, struct event_base *base) return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyLibeventEvents*)vk_calloc(1, sizeof(*e)); + e = (valkeyLibeventEvents *)vk_calloc(1, sizeof(*e)); if (e == NULL) return VALKEY_ERR; diff --git a/include/valkey/adapters/libhv.h b/include/valkey/adapters/libhv.h index 04e2d7e5..6e4c4824 100644 --- a/include/valkey/adapters/libhv.h +++ b/include/valkey/adapters/libhv.h @@ -1,17 +1,18 @@ #ifndef VALKEY_LIBHV_H #define VALKEY_LIBHV_H -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" + +#include typedef struct valkeyLibhvEvents { hio_t *io; htimer_t *timer; } valkeyLibhvEvents; -static void valkeyLibhvHandleEvents(hio_t* io) { - valkeyAsyncContext* context = (valkeyAsyncContext*)hevent_userdata(io); +static void valkeyLibhvHandleEvents(hio_t *io) { + valkeyAsyncContext *context = (valkeyAsyncContext *)hevent_userdata(io); int events = hio_events(io); int revents = hio_revents(io); if (context && (events & HV_READ) && (revents & HV_READ)) { @@ -23,27 +24,27 @@ static void valkeyLibhvHandleEvents(hio_t* io) { } static void valkeyLibhvAddRead(void *privdata) { - valkeyLibhvEvents* events = (valkeyLibhvEvents*)privdata; + valkeyLibhvEvents *events = (valkeyLibhvEvents *)privdata; hio_add(events->io, valkeyLibhvHandleEvents, HV_READ); } static void valkeyLibhvDelRead(void *privdata) { - valkeyLibhvEvents* events = (valkeyLibhvEvents*)privdata; + valkeyLibhvEvents *events = (valkeyLibhvEvents *)privdata; hio_del(events->io, HV_READ); } static void valkeyLibhvAddWrite(void *privdata) { - valkeyLibhvEvents* events = (valkeyLibhvEvents*)privdata; + valkeyLibhvEvents *events = (valkeyLibhvEvents *)privdata; hio_add(events->io, valkeyLibhvHandleEvents, HV_WRITE); } static void valkeyLibhvDelWrite(void *privdata) { - valkeyLibhvEvents* events = (valkeyLibhvEvents*)privdata; + valkeyLibhvEvents *events = (valkeyLibhvEvents *)privdata; hio_del(events->io, HV_WRITE); } static void valkeyLibhvCleanup(void *privdata) { - valkeyLibhvEvents* events = (valkeyLibhvEvents*)privdata; + valkeyLibhvEvents *events = (valkeyLibhvEvents *)privdata; if (events->timer) htimer_del(events->timer); @@ -54,17 +55,17 @@ static void valkeyLibhvCleanup(void *privdata) { vk_free(events); } -static void valkeyLibhvTimeout(htimer_t* timer) { - hio_t* io = (hio_t*)hevent_userdata(timer); - valkeyAsyncHandleTimeout((valkeyAsyncContext*)hevent_userdata(io)); +static void valkeyLibhvTimeout(htimer_t *timer) { + hio_t *io = (hio_t *)hevent_userdata(timer); + valkeyAsyncHandleTimeout((valkeyAsyncContext *)hevent_userdata(io)); } static void valkeyLibhvSetTimeout(void *privdata, struct timeval tv) { - valkeyLibhvEvents* events; + valkeyLibhvEvents *events; uint32_t millis; - hloop_t* loop; + hloop_t *loop; - events = (valkeyLibhvEvents*)privdata; + events = (valkeyLibhvEvents *)privdata; millis = tv.tv_sec * 1000 + tv.tv_usec / 1000; if (millis == 0) { @@ -84,17 +85,17 @@ static void valkeyLibhvSetTimeout(void *privdata, struct timeval tv) { } } -static int valkeyLibhvAttach(valkeyAsyncContext* ac, hloop_t* loop) { +static int valkeyLibhvAttach(valkeyAsyncContext *ac, hloop_t *loop) { valkeyContext *c = &(ac->c); valkeyLibhvEvents *events; - hio_t* io = NULL; + hio_t *io = NULL; if (ac->ev.data != NULL) { return VALKEY_ERR; } /* Create container struct to keep track of our io and any timer */ - events = (valkeyLibhvEvents*)vk_malloc(sizeof(*events)); + events = (valkeyLibhvEvents *)vk_malloc(sizeof(*events)); if (events == NULL) { return VALKEY_ERR; } @@ -110,11 +111,11 @@ static int valkeyLibhvAttach(valkeyAsyncContext* ac, hloop_t* loop) { events->io = io; events->timer = NULL; - ac->ev.addRead = valkeyLibhvAddRead; - ac->ev.delRead = valkeyLibhvDelRead; + ac->ev.addRead = valkeyLibhvAddRead; + ac->ev.delRead = valkeyLibhvDelRead; ac->ev.addWrite = valkeyLibhvAddWrite; ac->ev.delWrite = valkeyLibhvDelWrite; - ac->ev.cleanup = valkeyLibhvCleanup; + ac->ev.cleanup = valkeyLibhvCleanup; ac->ev.scheduleTimer = valkeyLibhvSetTimeout; ac->ev.data = events; diff --git a/include/valkey/adapters/libsdevent.h b/include/valkey/adapters/libsdevent.h index 36e3f29b..fdd44ce3 100644 --- a/include/valkey/adapters/libsdevent.h +++ b/include/valkey/adapters/libsdevent.h @@ -1,8 +1,9 @@ #ifndef VALKEY_LIBSDEVENT_H #define VALKEY_LIBSDEVENT_H -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" + +#include #define VALKEY_LIBSDEVENT_DELETED 0x01 #define VALKEY_LIBSDEVENT_ENTERED 0x02 @@ -31,7 +32,7 @@ static void valkeyLibsdeventDestroy(valkeyLibsdeventEvents *e) { static int valkeyLibsdeventTimeoutHandler(sd_event_source *s, uint64_t usec, void *userdata) { ((void)s); ((void)usec); - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; valkeyAsyncHandleTimeout(e->context); return 0; } @@ -39,12 +40,13 @@ static int valkeyLibsdeventTimeoutHandler(sd_event_source *s, uint64_t usec, voi static int valkeyLibsdeventHandler(sd_event_source *s, int fd, uint32_t event, void *userdata) { ((void)s); ((void)fd); - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; e->state |= VALKEY_LIBSDEVENT_ENTERED; -#define CHECK_DELETED() if (e->state & VALKEY_LIBSDEVENT_DELETED) {\ - valkeyLibsdeventDestroy(e);\ - return 0; \ +#define CHECK_DELETED() \ + if (e->state & VALKEY_LIBSDEVENT_DELETED) { \ + valkeyLibsdeventDestroy(e); \ + return 0; \ } if ((event & EPOLLIN) && e->context && (e->state & VALKEY_LIBSDEVENT_DELETED) == 0) { @@ -64,7 +66,7 @@ static int valkeyLibsdeventHandler(sd_event_source *s, int fd, uint32_t event, v } static void valkeyLibsdeventAddRead(void *userdata) { - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; if (e->flags & EPOLLIN) { return; @@ -80,7 +82,7 @@ static void valkeyLibsdeventAddRead(void *userdata) { } static void valkeyLibsdeventDelRead(void *userdata) { - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; e->flags &= ~EPOLLIN; @@ -92,7 +94,7 @@ static void valkeyLibsdeventDelRead(void *userdata) { } static void valkeyLibsdeventAddWrite(void *userdata) { - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; if (e->flags & EPOLLOUT) { return; @@ -108,7 +110,7 @@ static void valkeyLibsdeventAddWrite(void *userdata) { } static void valkeyLibsdeventDelWrite(void *userdata) { - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; e->flags &= ~EPOLLOUT; @@ -120,7 +122,7 @@ static void valkeyLibsdeventDelWrite(void *userdata) { } static void valkeyLibsdeventCleanup(void *userdata) { - valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents*)userdata; + valkeyLibsdeventEvents *e = (valkeyLibsdeventEvents *)userdata; if (!e) { return; @@ -153,7 +155,7 @@ static int valkeyLibsdeventAttach(valkeyAsyncContext *ac, struct sd_event *event return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyLibsdeventEvents*)vk_calloc(1, sizeof(*e)); + e = (valkeyLibsdeventEvents *)vk_calloc(1, sizeof(*e)); if (e == NULL) return VALKEY_ERR; diff --git a/include/valkey/adapters/libuv.h b/include/valkey/adapters/libuv.h index 80c4b2ae..be5461f8 100644 --- a/include/valkey/adapters/libuv.h +++ b/include/valkey/adapters/libuv.h @@ -31,23 +31,23 @@ #ifndef VALKEY_LIBUV_H #define VALKEY_LIBUV_H -#include -#include -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" #include "../valkeycluster.h" + +#include #include +#include typedef struct valkeyLibuvEvents { - valkeyAsyncContext* context; - uv_poll_t handle; - uv_timer_t timer; - int events; + valkeyAsyncContext *context; + uv_poll_t handle; + uv_timer_t timer; + int events; } valkeyLibuvEvents; - -static void valkeyLibuvPoll(uv_poll_t* handle, int status, int events) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)handle->data; +static void valkeyLibuvPoll(uv_poll_t *handle, int status, int events) { + valkeyLibuvEvents *p = (valkeyLibuvEvents *)handle->data; int ev = (status ? p->events : events); if (p->context != NULL && (ev & UV_READABLE)) { @@ -58,9 +58,8 @@ static void valkeyLibuvPoll(uv_poll_t* handle, int status, int events) { } } - static void valkeyLibuvAddRead(void *privdata) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; if (p->events & UV_READABLE) { return; @@ -71,9 +70,8 @@ static void valkeyLibuvAddRead(void *privdata) { uv_poll_start(&p->handle, p->events, valkeyLibuvPoll); } - static void valkeyLibuvDelRead(void *privdata) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; p->events &= ~UV_READABLE; @@ -84,9 +82,8 @@ static void valkeyLibuvDelRead(void *privdata) { } } - static void valkeyLibuvAddWrite(void *privdata) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; if (p->events & UV_WRITABLE) { return; @@ -97,9 +94,8 @@ static void valkeyLibuvAddWrite(void *privdata) { uv_poll_start(&p->handle, p->events, valkeyLibuvPoll); } - static void valkeyLibuvDelWrite(void *privdata) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; p->events &= ~UV_WRITABLE; @@ -111,7 +107,7 @@ static void valkeyLibuvDelWrite(void *privdata) { } static void on_timer_close(uv_handle_t *handle) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)handle->data; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)handle->data; p->timer.data = NULL; if (!p->handle.data) { // both timer and handle are closed @@ -121,7 +117,7 @@ static void on_timer_close(uv_handle_t *handle) { } static void on_handle_close(uv_handle_t *handle) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)handle->data; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)handle->data; p->handle.data = NULL; if (!p->timer.data) { // timer never started, or timer already destroyed @@ -139,12 +135,12 @@ static void valkeyLibuvTimeout(uv_timer_t *timer, int status) { #else static void valkeyLibuvTimeout(uv_timer_t *timer) { #endif - valkeyLibuvEvents *e = (valkeyLibuvEvents*)timer->data; + valkeyLibuvEvents *e = (valkeyLibuvEvents *)timer->data; valkeyAsyncHandleTimeout(e->context); } static void valkeyLibuvSetTimeout(void *privdata, struct timeval tv) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; uint64_t millsec = tv.tv_sec * 1000 + tv.tv_usec / 1000.0; if (!p->timer.data) { @@ -160,31 +156,30 @@ static void valkeyLibuvSetTimeout(void *privdata, struct timeval tv) { } static void valkeyLibuvCleanup(void *privdata) { - valkeyLibuvEvents* p = (valkeyLibuvEvents*)privdata; + valkeyLibuvEvents *p = (valkeyLibuvEvents *)privdata; p->context = NULL; // indicate that context might no longer exist if (p->timer.data) { - uv_close((uv_handle_t*)&p->timer, on_timer_close); + uv_close((uv_handle_t *)&p->timer, on_timer_close); } - uv_close((uv_handle_t*)&p->handle, on_handle_close); + uv_close((uv_handle_t *)&p->handle, on_handle_close); } - -static int valkeyLibuvAttach(valkeyAsyncContext* ac, uv_loop_t* loop) { +static int valkeyLibuvAttach(valkeyAsyncContext *ac, uv_loop_t *loop) { valkeyContext *c = &(ac->c); if (ac->ev.data != NULL) { return VALKEY_ERR; } - ac->ev.addRead = valkeyLibuvAddRead; - ac->ev.delRead = valkeyLibuvDelRead; - ac->ev.addWrite = valkeyLibuvAddWrite; - ac->ev.delWrite = valkeyLibuvDelWrite; - ac->ev.cleanup = valkeyLibuvCleanup; - ac->ev.scheduleTimer = valkeyLibuvSetTimeout; + ac->ev.addRead = valkeyLibuvAddRead; + ac->ev.delRead = valkeyLibuvDelRead; + ac->ev.addWrite = valkeyLibuvAddWrite; + ac->ev.delWrite = valkeyLibuvDelWrite; + ac->ev.cleanup = valkeyLibuvCleanup; + ac->ev.scheduleTimer = valkeyLibuvSetTimeout; - valkeyLibuvEvents* p = (valkeyLibuvEvents*)vk_malloc(sizeof(*p)); + valkeyLibuvEvents *p = (valkeyLibuvEvents *)vk_malloc(sizeof(*p)); if (p == NULL) return VALKEY_ERR; @@ -195,9 +190,9 @@ static int valkeyLibuvAttach(valkeyAsyncContext* ac, uv_loop_t* loop) { return VALKEY_ERR; } - ac->ev.data = p; + ac->ev.data = p; p->handle.data = p; - p->context = ac; + p->context = ac; return VALKEY_OK; } diff --git a/include/valkey/adapters/macosx.h b/include/valkey/adapters/macosx.h index 417b1fa2..1c621e15 100644 --- a/include/valkey/adapters/macosx.h +++ b/include/valkey/adapters/macosx.h @@ -34,10 +34,10 @@ #ifndef VALKEY_MACOSX_H #define VALKEY_MACOSX_H -#include - -#include "../valkey.h" #include "../async.h" +#include "../valkey.h" + +#include typedef struct { valkeyAsyncContext *context; @@ -45,13 +45,13 @@ typedef struct { CFRunLoopSourceRef sourceRef; } ValkeyRunLoop; -static int freeValkeyRunLoop(ValkeyRunLoop* valkeyRunLoop) { - if( valkeyRunLoop != NULL ) { - if( valkeyRunLoop->sourceRef != NULL ) { +static int freeValkeyRunLoop(ValkeyRunLoop *valkeyRunLoop) { + if (valkeyRunLoop != NULL) { + if (valkeyRunLoop->sourceRef != NULL) { CFRunLoopSourceInvalidate(valkeyRunLoop->sourceRef); CFRelease(valkeyRunLoop->sourceRef); } - if( valkeyRunLoop->socketRef != NULL ) { + if (valkeyRunLoop->socketRef != NULL) { CFSocketInvalidate(valkeyRunLoop->socketRef); CFRelease(valkeyRunLoop->socketRef); } @@ -61,44 +61,44 @@ static int freeValkeyRunLoop(ValkeyRunLoop* valkeyRunLoop) { } static void valkeyMacOSAddRead(void *privdata) { - ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop*)privdata; + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)privdata; CFSocketEnableCallBacks(valkeyRunLoop->socketRef, kCFSocketReadCallBack); } static void valkeyMacOSDelRead(void *privdata) { - ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop*)privdata; + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)privdata; CFSocketDisableCallBacks(valkeyRunLoop->socketRef, kCFSocketReadCallBack); } static void valkeyMacOSAddWrite(void *privdata) { - ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop*)privdata; + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)privdata; CFSocketEnableCallBacks(valkeyRunLoop->socketRef, kCFSocketWriteCallBack); } static void valkeyMacOSDelWrite(void *privdata) { - ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop*)privdata; + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)privdata; CFSocketDisableCallBacks(valkeyRunLoop->socketRef, kCFSocketWriteCallBack); } static void valkeyMacOSCleanup(void *privdata) { - ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop*)privdata; + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)privdata; freeValkeyRunLoop(valkeyRunLoop); } static void valkeyMacOSAsyncCallback(CFSocketRef __unused s, CFSocketCallBackType callbackType, CFDataRef __unused address, const void __unused *data, void *info) { - valkeyAsyncContext* context = (valkeyAsyncContext*) info; + valkeyAsyncContext *context = (valkeyAsyncContext *)info; switch (callbackType) { - case kCFSocketReadCallBack: - valkeyAsyncHandleRead(context); - break; + case kCFSocketReadCallBack: + valkeyAsyncHandleRead(context); + break; - case kCFSocketWriteCallBack: - valkeyAsyncHandleWrite(context); - break; + case kCFSocketWriteCallBack: + valkeyAsyncHandleWrite(context); + break; - default: - break; + default: + break; } } @@ -106,33 +106,36 @@ static int valkeyMacOSAttach(valkeyAsyncContext *valkeyAsyncCtx, CFRunLoopRef ru valkeyContext *valkeyCtx = &(valkeyAsyncCtx->c); /* Nothing should be attached when something is already attached */ - if( valkeyAsyncCtx->ev.data != NULL ) return VALKEY_ERR; + if (valkeyAsyncCtx->ev.data != NULL) + return VALKEY_ERR; - ValkeyRunLoop* valkeyRunLoop = (ValkeyRunLoop*) vk_calloc(1, sizeof(ValkeyRunLoop)); + ValkeyRunLoop *valkeyRunLoop = (ValkeyRunLoop *)vk_calloc(1, sizeof(ValkeyRunLoop)); if (valkeyRunLoop == NULL) return VALKEY_ERR; /* Setup valkey stuff */ valkeyRunLoop->context = valkeyAsyncCtx; - valkeyAsyncCtx->ev.addRead = valkeyMacOSAddRead; - valkeyAsyncCtx->ev.delRead = valkeyMacOSDelRead; + valkeyAsyncCtx->ev.addRead = valkeyMacOSAddRead; + valkeyAsyncCtx->ev.delRead = valkeyMacOSDelRead; valkeyAsyncCtx->ev.addWrite = valkeyMacOSAddWrite; valkeyAsyncCtx->ev.delWrite = valkeyMacOSDelWrite; - valkeyAsyncCtx->ev.cleanup = valkeyMacOSCleanup; - valkeyAsyncCtx->ev.data = valkeyRunLoop; + valkeyAsyncCtx->ev.cleanup = valkeyMacOSCleanup; + valkeyAsyncCtx->ev.data = valkeyRunLoop; /* Initialize and install read/write events */ - CFSocketContext socketCtx = { 0, valkeyAsyncCtx, NULL, NULL, NULL }; + CFSocketContext socketCtx = {0, valkeyAsyncCtx, NULL, NULL, NULL}; valkeyRunLoop->socketRef = CFSocketCreateWithNative(NULL, valkeyCtx->fd, - kCFSocketReadCallBack | kCFSocketWriteCallBack, - valkeyMacOSAsyncCallback, - &socketCtx); - if( !valkeyRunLoop->socketRef ) return freeValkeyRunLoop(valkeyRunLoop); + kCFSocketReadCallBack | kCFSocketWriteCallBack, + valkeyMacOSAsyncCallback, + &socketCtx); + if (!valkeyRunLoop->socketRef) + return freeValkeyRunLoop(valkeyRunLoop); valkeyRunLoop->sourceRef = CFSocketCreateRunLoopSource(NULL, valkeyRunLoop->socketRef, 0); - if( !valkeyRunLoop->sourceRef ) return freeValkeyRunLoop(valkeyRunLoop); + if (!valkeyRunLoop->sourceRef) + return freeValkeyRunLoop(valkeyRunLoop); CFRunLoopAddSource(runLoop, valkeyRunLoop->sourceRef, kCFRunLoopDefaultMode); @@ -140,4 +143,3 @@ static int valkeyMacOSAttach(valkeyAsyncContext *valkeyAsyncCtx, CFRunLoopRef ru } #endif - diff --git a/include/valkey/adapters/poll.h b/include/valkey/adapters/poll.h index ecee5244..c039a8b7 100644 --- a/include/valkey/adapters/poll.h +++ b/include/valkey/adapters/poll.h @@ -4,12 +4,13 @@ #include "../async.h" #include "../sockcompat.h" -#include // for memset + #include +#include // for memset /* Values to return from valkeyPollTick */ -#define VALKEY_POLL_HANDLED_READ 1 -#define VALKEY_POLL_HANDLED_WRITE 2 +#define VALKEY_POLL_HANDLED_READ 1 +#define VALKEY_POLL_HANDLED_WRITE 2 #define VALKEY_POLL_HANDLED_TIMEOUT 4 /* An adapter to allow manual polling of the async context by checking the state @@ -34,7 +35,7 @@ static double valkeyPollTimevalToDouble(struct timeval *tv) { static double valkeyPollGetNow(void) { #ifndef _MSC_VER struct timeval tv; - gettimeofday(&tv,NULL); + gettimeofday(&tv, NULL); return valkeyPollTimevalToDouble(&tv); #else FILETIME ft; @@ -56,7 +57,7 @@ static int valkeyPollTick(valkeyAsyncContext *ac, double timeout) { int ns; int itimeout; - valkeyPollEvents *e = (valkeyPollEvents*)ac->ev.data; + valkeyPollEvents *e = (valkeyPollEvents *)ac->ev.data; if (!e) return 0; @@ -127,27 +128,27 @@ static int valkeyPollTick(valkeyAsyncContext *ac, double timeout) { } static void valkeyPollAddRead(void *data) { - valkeyPollEvents *e = (valkeyPollEvents*)data; + valkeyPollEvents *e = (valkeyPollEvents *)data; e->reading = 1; } static void valkeyPollDelRead(void *data) { - valkeyPollEvents *e = (valkeyPollEvents*)data; + valkeyPollEvents *e = (valkeyPollEvents *)data; e->reading = 0; } static void valkeyPollAddWrite(void *data) { - valkeyPollEvents *e = (valkeyPollEvents*)data; + valkeyPollEvents *e = (valkeyPollEvents *)data; e->writing = 1; } static void valkeyPollDelWrite(void *data) { - valkeyPollEvents *e = (valkeyPollEvents*)data; + valkeyPollEvents *e = (valkeyPollEvents *)data; e->writing = 0; } static void valkeyPollCleanup(void *data) { - valkeyPollEvents *e = (valkeyPollEvents*)data; + valkeyPollEvents *e = (valkeyPollEvents *)data; /* if we are currently processing a tick, postpone deletion */ if (e->in_tick) @@ -156,9 +157,8 @@ static void valkeyPollCleanup(void *data) { vk_free(e); } -static void valkeyPollScheduleTimer(void *data, struct timeval tv) -{ - valkeyPollEvents *e = (valkeyPollEvents*)data; +static void valkeyPollScheduleTimer(void *data, struct timeval tv) { + valkeyPollEvents *e = (valkeyPollEvents *)data; double now = valkeyPollGetNow(); e->deadline = now + valkeyPollTimevalToDouble(&tv); } @@ -172,7 +172,7 @@ static int valkeyPollAttach(valkeyAsyncContext *ac) { return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyPollEvents*)vk_malloc(sizeof(*e)); + e = (valkeyPollEvents *)vk_malloc(sizeof(*e)); if (e == NULL) return VALKEY_ERR; memset(e, 0, sizeof(*e)); diff --git a/include/valkey/adapters/qt.h b/include/valkey/adapters/qt.h index 7641f72e..da67e421 100644 --- a/include/valkey/adapters/qt.h +++ b/include/valkey/adapters/qt.h @@ -25,9 +25,10 @@ #ifndef VALKEY_QT_H #define VALKEY_QT_H -#include #include "../async.h" +#include + static void ValkeyQtAddRead(void *); static void ValkeyQtDelRead(void *); static void ValkeyQtAddWrite(void *); @@ -38,98 +39,97 @@ class ValkeyQtAdapter : public QObject { Q_OBJECT - friend - void ValkeyQtAddRead(void * adapter) { - ValkeyQtAdapter * a = static_cast(adapter); + friend void ValkeyQtAddRead(void *adapter) { + ValkeyQtAdapter *a = static_cast(adapter); a->addRead(); } - friend - void ValkeyQtDelRead(void * adapter) { - ValkeyQtAdapter * a = static_cast(adapter); + friend void ValkeyQtDelRead(void *adapter) { + ValkeyQtAdapter *a = static_cast(adapter); a->delRead(); } - friend - void ValkeyQtAddWrite(void * adapter) { - ValkeyQtAdapter * a = static_cast(adapter); + friend void ValkeyQtAddWrite(void *adapter) { + ValkeyQtAdapter *a = static_cast(adapter); a->addWrite(); } - friend - void ValkeyQtDelWrite(void * adapter) { - ValkeyQtAdapter * a = static_cast(adapter); + friend void ValkeyQtDelWrite(void *adapter) { + ValkeyQtAdapter *a = static_cast(adapter); a->delWrite(); } - friend - void ValkeyQtCleanup(void * adapter) { - ValkeyQtAdapter * a = static_cast(adapter); + friend void ValkeyQtCleanup(void *adapter) { + ValkeyQtAdapter *a = static_cast(adapter); a->cleanup(); } - public: - ValkeyQtAdapter(QObject * parent = 0) - : QObject(parent), m_ctx(0), m_read(0), m_write(0) { } + public: + ValkeyQtAdapter(QObject *parent = 0) + : QObject(parent), m_ctx(0), m_read(0), m_write(0) {} - ~ValkeyQtAdapter() { - if (m_ctx != 0) { - m_ctx->ev.data = NULL; - } + ~ValkeyQtAdapter() { + if (m_ctx != 0) { + m_ctx->ev.data = NULL; } + } - int setContext(valkeyAsyncContext * ac) { - if (ac->ev.data != NULL) { - return VALKEY_ERR; - } - m_ctx = ac; - m_ctx->ev.data = this; - m_ctx->ev.addRead = ValkeyQtAddRead; - m_ctx->ev.delRead = ValkeyQtDelRead; - m_ctx->ev.addWrite = ValkeyQtAddWrite; - m_ctx->ev.delWrite = ValkeyQtDelWrite; - m_ctx->ev.cleanup = ValkeyQtCleanup; - return VALKEY_OK; + int setContext(valkeyAsyncContext *ac) { + if (ac->ev.data != NULL) { + return VALKEY_ERR; } + m_ctx = ac; + m_ctx->ev.data = this; + m_ctx->ev.addRead = ValkeyQtAddRead; + m_ctx->ev.delRead = ValkeyQtDelRead; + m_ctx->ev.addWrite = ValkeyQtAddWrite; + m_ctx->ev.delWrite = ValkeyQtDelWrite; + m_ctx->ev.cleanup = ValkeyQtCleanup; + return VALKEY_OK; + } - private: - void addRead() { - if (m_read) return; - m_read = new QSocketNotifier(m_ctx->c.fd, QSocketNotifier::Read, 0); - connect(m_read, SIGNAL(activated(int)), this, SLOT(read())); - } + private: + void addRead() { + if (m_read) + return; + m_read = new QSocketNotifier(m_ctx->c.fd, QSocketNotifier::Read, 0); + connect(m_read, SIGNAL(activated(int)), this, SLOT(read())); + } - void delRead() { - if (!m_read) return; - delete m_read; - m_read = 0; - } + void delRead() { + if (!m_read) + return; + delete m_read; + m_read = 0; + } - void addWrite() { - if (m_write) return; - m_write = new QSocketNotifier(m_ctx->c.fd, QSocketNotifier::Write, 0); - connect(m_write, SIGNAL(activated(int)), this, SLOT(write())); - } + void addWrite() { + if (m_write) + return; + m_write = new QSocketNotifier(m_ctx->c.fd, QSocketNotifier::Write, 0); + connect(m_write, SIGNAL(activated(int)), this, SLOT(write())); + } - void delWrite() { - if (!m_write) return; - delete m_write; - m_write = 0; - } + void delWrite() { + if (!m_write) + return; + delete m_write; + m_write = 0; + } - void cleanup() { - delRead(); - delWrite(); - } + void cleanup() { + delRead(); + delWrite(); + } - private slots: - void read() { valkeyAsyncHandleRead(m_ctx); } - void write() { valkeyAsyncHandleWrite(m_ctx); } + private slots: + void read() { valkeyAsyncHandleRead(m_ctx); } + void write() { valkeyAsyncHandleWrite(m_ctx); } - private: - valkeyAsyncContext * m_ctx; - QSocketNotifier * m_read; - QSocketNotifier * m_write; + private: + valkeyAsyncContext *m_ctx; + QSocketNotifier *m_read; + QSocketNotifier *m_write; }; #endif /* !VALKEY_QT_H */ diff --git a/include/valkey/adapters/valkeymoduleapi.h b/include/valkey/adapters/valkeymoduleapi.h index f72daa74..46015199 100644 --- a/include/valkey/adapters/valkeymoduleapi.h +++ b/include/valkey/adapters/valkeymoduleapi.h @@ -1,10 +1,9 @@ #ifndef VALKEY_VALKEYMODULEAPI_H #define VALKEY_VALKEYMODULEAPI_H -#include "valkeymodule.h" - #include "../async.h" #include "../valkey.h" +#include "valkeymodule.h" #include @@ -18,23 +17,23 @@ typedef struct valkeyModuleEvents { } valkeyModuleEvents; static inline void valkeyModuleReadEvent(int fd, void *privdata, int mask) { - (void) fd; - (void) mask; + (void)fd; + (void)mask; - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; valkeyAsyncHandleRead(e->context); } static inline void valkeyModuleWriteEvent(int fd, void *privdata, int mask) { - (void) fd; - (void) mask; + (void)fd; + (void)mask; - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; valkeyAsyncHandleWrite(e->context); } static inline void valkeyModuleAddRead(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; if (!e->reading) { e->reading = 1; ValkeyModule_EventLoopAdd(e->fd, VALKEYMODULE_EVENTLOOP_READABLE, valkeyModuleReadEvent, e); @@ -42,7 +41,7 @@ static inline void valkeyModuleAddRead(void *privdata) { } static inline void valkeyModuleDelRead(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; if (e->reading) { e->reading = 0; ValkeyModule_EventLoopDel(e->fd, VALKEYMODULE_EVENTLOOP_READABLE); @@ -50,7 +49,7 @@ static inline void valkeyModuleDelRead(void *privdata) { } static inline void valkeyModuleAddWrite(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; if (!e->writing) { e->writing = 1; ValkeyModule_EventLoopAdd(e->fd, VALKEYMODULE_EVENTLOOP_WRITABLE, valkeyModuleWriteEvent, e); @@ -58,7 +57,7 @@ static inline void valkeyModuleAddWrite(void *privdata) { } static inline void valkeyModuleDelWrite(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; if (e->writing) { e->writing = 0; ValkeyModule_EventLoopDel(e->fd, VALKEYMODULE_EVENTLOOP_WRITABLE); @@ -66,7 +65,7 @@ static inline void valkeyModuleDelWrite(void *privdata) { } static inline void valkeyModuleStopTimer(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; if (e->timer_active) { ValkeyModule_StopTimer(e->module_ctx, e->timer_id, NULL); } @@ -74,7 +73,7 @@ static inline void valkeyModuleStopTimer(void *privdata) { } static inline void valkeyModuleCleanup(void *privdata) { - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; valkeyModuleDelRead(privdata); valkeyModuleDelWrite(privdata); valkeyModuleStopTimer(privdata); @@ -82,15 +81,15 @@ static inline void valkeyModuleCleanup(void *privdata) { } static inline void valkeyModuleTimeout(ValkeyModuleCtx *ctx, void *privdata) { - (void) ctx; + (void)ctx; - valkeyModuleEvents *e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; e->timer_active = 0; valkeyAsyncHandleTimeout(e->context); } static inline void valkeyModuleSetTimeout(void *privdata, struct timeval tv) { - valkeyModuleEvents* e = (valkeyModuleEvents*)privdata; + valkeyModuleEvents *e = (valkeyModuleEvents *)privdata; valkeyModuleStopTimer(privdata); @@ -119,7 +118,7 @@ static inline int valkeyModuleAttach(valkeyAsyncContext *ac, ValkeyModuleCtx *mo return VALKEY_ERR; /* Create container for context and r/w events */ - e = (valkeyModuleEvents*)vk_malloc(sizeof(*e)); + e = (valkeyModuleEvents *)vk_malloc(sizeof(*e)); if (e == NULL) return VALKEY_ERR; diff --git a/include/valkey/alloc.h b/include/valkey/alloc.h index 395c6197..26d24f75 100644 --- a/include/valkey/alloc.h +++ b/include/valkey/alloc.h @@ -41,10 +41,10 @@ extern "C" { /* Structure pointing to our actually configured allocators */ typedef struct valkeyAllocFuncs { void *(*mallocFn)(size_t); - void *(*callocFn)(size_t,size_t); - void *(*reallocFn)(void*,size_t); - char *(*strdupFn)(const char*); - void (*freeFn)(void*); + void *(*callocFn)(size_t, size_t); + void *(*reallocFn)(void *, size_t); + char *(*strdupFn)(const char *); + void (*freeFn)(void *); } valkeyAllocFuncs; valkeyAllocFuncs valkeySetAllocators(valkeyAllocFuncs *fns); diff --git a/include/valkey/async.h b/include/valkey/async.h index 0c17eca2..820c9571 100644 --- a/include/valkey/async.h +++ b/include/valkey/async.h @@ -45,10 +45,10 @@ extern "C" { #endif struct valkeyAsyncContext; /* need forward declaration of valkeyAsyncContext */ -struct dict; /* dictionary header is included in async.c */ +struct dict; /* dictionary header is included in async.c */ /* Reply callback prototype and container */ -typedef void (valkeyCallbackFn)(struct valkeyAsyncContext*, void*, void*); +typedef void(valkeyCallbackFn)(struct valkeyAsyncContext *, void *, void *); typedef struct valkeyCallback { struct valkeyCallback *next; /* simple singly linked list */ valkeyCallbackFn *fn; @@ -63,9 +63,9 @@ typedef struct valkeyCallbackList { } valkeyCallbackList; /* Connection callback prototypes */ -typedef void (valkeyDisconnectCallback)(const struct valkeyAsyncContext*, int status); -typedef void (valkeyConnectCallback)(const struct valkeyAsyncContext*, int status); -typedef void (valkeyConnectCallbackNC)(struct valkeyAsyncContext *, int status); +typedef void(valkeyDisconnectCallback)(const struct valkeyAsyncContext *, int status); +typedef void(valkeyConnectCallback)(const struct valkeyAsyncContext *, int status); +typedef void(valkeyConnectCallbackNC)(struct valkeyAsyncContext *, int status); typedef void(valkeyTimerCallback)(void *timer, void *privdata); /* Context for an async connection to Valkey */ @@ -127,7 +127,7 @@ valkeyAsyncContext *valkeyAsyncConnectWithOptions(const valkeyOptions *options); valkeyAsyncContext *valkeyAsyncConnect(const char *ip, int port); valkeyAsyncContext *valkeyAsyncConnectBind(const char *ip, int port, const char *source_addr); valkeyAsyncContext *valkeyAsyncConnectBindWithReuse(const char *ip, int port, - const char *source_addr); + const char *source_addr); valkeyAsyncContext *valkeyAsyncConnectUnix(const char *path); int valkeyAsyncSetConnectCallback(valkeyAsyncContext *ac, valkeyConnectCallback *fn); int valkeyAsyncSetConnectCallbackNC(valkeyAsyncContext *ac, valkeyConnectCallbackNC *fn); diff --git a/include/valkey/dict.h b/include/valkey/dict.h index d059f6b3..d064e9e5 100644 --- a/include/valkey/dict.h +++ b/include/valkey/dict.h @@ -40,7 +40,7 @@ #define DICT_ERR 1 /* Unused arguments generate annoying warnings... */ -#define DICT_NOTUSED(V) ((void) V) +#define DICT_NOTUSED(V) ((void)V) typedef struct dictEntry { void *key; @@ -73,35 +73,37 @@ typedef struct dictIterator { } dictIterator; /* This is the initial size of every hash table */ -#define DICT_HT_INITIAL_SIZE 4 +#define DICT_HT_INITIAL_SIZE 4 /* ------------------------------- Macros ------------------------------------*/ #define dictFreeEntryVal(ht, entry) \ - if ((ht)->type->valDestructor) \ - (ht)->type->valDestructor((ht)->privdata, (entry)->val) + if ((ht)->type->valDestructor) \ + (ht)->type->valDestructor((ht)->privdata, (entry)->val) -#define dictSetHashVal(ht, entry, _val_) do { \ - if ((ht)->type->valDup) \ - entry->val = (ht)->type->valDup((ht)->privdata, _val_); \ - else \ - entry->val = (_val_); \ -} while(0) +#define dictSetHashVal(ht, entry, _val_) \ + do { \ + if ((ht)->type->valDup) \ + entry->val = (ht)->type->valDup((ht)->privdata, _val_); \ + else \ + entry->val = (_val_); \ + } while (0) #define dictFreeEntryKey(ht, entry) \ - if ((ht)->type->keyDestructor) \ - (ht)->type->keyDestructor((ht)->privdata, (entry)->key) - -#define dictSetHashKey(ht, entry, _key_) do { \ - if ((ht)->type->keyDup) \ - entry->key = (ht)->type->keyDup((ht)->privdata, _key_); \ - else \ - entry->key = (_key_); \ -} while(0) - -#define dictCompareHashKeys(ht, key1, key2) \ - (((ht)->type->keyCompare) ? \ - (ht)->type->keyCompare((ht)->privdata, key1, key2) : \ - (key1) == (key2)) + if ((ht)->type->keyDestructor) \ + (ht)->type->keyDestructor((ht)->privdata, (entry)->key) + +#define dictSetHashKey(ht, entry, _key_) \ + do { \ + if ((ht)->type->keyDup) \ + entry->key = (ht)->type->keyDup((ht)->privdata, _key_); \ + else \ + entry->key = (_key_); \ + } while (0) + +#define dictCompareHashKeys(ht, key1, key2) \ + (((ht)->type->keyCompare) ? \ + (ht)->type->keyCompare((ht)->privdata, key1, key2) : \ + (key1) == (key2)) #define dictHashKey(ht, key) (ht)->type->hashFunction(key) @@ -118,7 +120,7 @@ int dictAdd(dict *ht, void *key, void *val); int dictReplace(dict *ht, void *key, void *val); int dictDelete(dict *ht, const void *key); void dictRelease(dict *ht); -dictEntry * dictFind(dict *ht, const void *key); +dictEntry *dictFind(dict *ht, const void *key); void dictInitIterator(dictIterator *iter, dict *ht); dictEntry *dictNext(dictIterator *iter); diff --git a/include/valkey/read.h b/include/valkey/read.h index 8fb22832..cd6dd7fc 100644 --- a/include/valkey/read.h +++ b/include/valkey/read.h @@ -29,7 +29,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ - #ifndef VALKEY_READ_H #define VALKEY_READ_H #include /* for size_t */ @@ -41,12 +40,12 @@ * error that occurred. VALKEY_ERR_IO means there was an I/O error and you * should use the "errno" variable to find out what is wrong. * For other values, the "errstr" field will hold a description. */ -#define VALKEY_ERR_IO 1 /* Error in read or write */ -#define VALKEY_ERR_EOF 3 /* End of file */ +#define VALKEY_ERR_IO 1 /* Error in read or write */ +#define VALKEY_ERR_EOF 3 /* End of file */ #define VALKEY_ERR_PROTOCOL 4 /* Protocol error */ -#define VALKEY_ERR_OOM 5 /* Out of memory */ -#define VALKEY_ERR_TIMEOUT 6 /* Timed out */ -#define VALKEY_ERR_OTHER 2 /* Everything else... */ +#define VALKEY_ERR_OOM 5 /* Out of memory */ +#define VALKEY_ERR_TIMEOUT 6 /* Timed out */ +#define VALKEY_ERR_OTHER 2 /* Everything else... */ #define VALKEY_REPLY_STRING 1 #define VALKEY_REPLY_ARRAY 2 @@ -64,10 +63,10 @@ #define VALKEY_REPLY_VERB 14 /* Default max unused reader buffer. */ -#define VALKEY_READER_MAX_BUF (1024*16) +#define VALKEY_READER_MAX_BUF (1024 * 16) /* Default multi-bulk element limit */ -#define VALKEY_READER_MAX_ARRAY_ELEMENTS ((1LL<<32) - 1) +#define VALKEY_READER_MAX_ARRAY_ELEMENTS ((1LL << 32) - 1) #ifdef __cplusplus extern "C" { @@ -75,37 +74,37 @@ extern "C" { typedef struct valkeyReadTask { int type; - long long elements; /* number of elements in multibulk container */ - int idx; /* index in parent (array) object */ - void *obj; /* holds user-generated value for a read task */ + long long elements; /* number of elements in multibulk container */ + int idx; /* index in parent (array) object */ + void *obj; /* holds user-generated value for a read task */ struct valkeyReadTask *parent; /* parent task */ - void *privdata; /* user-settable arbitrary field */ + void *privdata; /* user-settable arbitrary field */ } valkeyReadTask; typedef struct valkeyReplyObjectFunctions { - void *(*createString)(const valkeyReadTask*, char*, size_t); - void *(*createArray)(const valkeyReadTask*, size_t); - void *(*createInteger)(const valkeyReadTask*, long long); - void *(*createDouble)(const valkeyReadTask*, double, char*, size_t); - void *(*createNil)(const valkeyReadTask*); - void *(*createBool)(const valkeyReadTask*, int); - void (*freeObject)(void*); + void *(*createString)(const valkeyReadTask *, char *, size_t); + void *(*createArray)(const valkeyReadTask *, size_t); + void *(*createInteger)(const valkeyReadTask *, long long); + void *(*createDouble)(const valkeyReadTask *, double, char *, size_t); + void *(*createNil)(const valkeyReadTask *); + void *(*createBool)(const valkeyReadTask *, int); + void (*freeObject)(void *); } valkeyReplyObjectFunctions; typedef struct valkeyReader { - int err; /* Error flags, 0 when there is no error */ + int err; /* Error flags, 0 when there is no error */ char errstr[128]; /* String representation of error when applicable */ - char *buf; /* Read buffer */ - size_t pos; /* Buffer cursor */ - size_t len; /* Buffer length */ - size_t maxbuf; /* Max length of unused buffer */ + char *buf; /* Read buffer */ + size_t pos; /* Buffer cursor */ + size_t len; /* Buffer length */ + size_t maxbuf; /* Max length of unused buffer */ long long maxelements; /* Max multi-bulk elements */ valkeyReadTask **task; int tasks; - int ridx; /* Index of current read task */ + int ridx; /* Index of current read task */ void *reply; /* Temporary reply pointer */ valkeyReplyObjectFunctions *fn; @@ -118,9 +117,9 @@ void valkeyReaderFree(valkeyReader *r); int valkeyReaderFeed(valkeyReader *r, const char *buf, size_t len); int valkeyReaderGetReply(valkeyReader *r, void **reply); -#define valkeyReaderSetPrivdata(_r, _p) (int)(((valkeyReader*)(_r))->privdata = (_p)) -#define valkeyReaderGetObject(_r) (((valkeyReader*)(_r))->reply) -#define valkeyReaderGetError(_r) (((valkeyReader*)(_r))->errstr) +#define valkeyReaderSetPrivdata(_r, _p) (int)(((valkeyReader *)(_r))->privdata = (_p)) +#define valkeyReaderGetObject(_r) (((valkeyReader *)(_r))->reply) +#define valkeyReaderGetError(_r) (((valkeyReader *)(_r))->errstr) #ifdef __cplusplus } diff --git a/include/valkey/sds.h b/include/valkey/sds.h index 3cef6b58..55390af2 100644 --- a/include/valkey/sds.h +++ b/include/valkey/sds.h @@ -33,7 +33,7 @@ #ifndef __SDS_H #define __SDS_H -#define SDS_MAX_PREALLOC (1024*1024) +#define SDS_MAX_PREALLOC (1024 * 1024) #ifdef _MSC_VER #include typedef SSIZE_T ssize_t; @@ -47,182 +47,178 @@ typedef SSIZE_T ssize_t; #endif #endif -#include #include #include +#include typedef char *sds; /* Note: sdshdr5 is never used, we just access the flags byte directly. * However is here to document the layout of type 5 SDS strings. */ -struct __attribute__ ((__packed__)) sdshdr5 { +struct __attribute__((__packed__)) sdshdr5 { unsigned char flags; /* 3 lsb of type, and 5 msb of string length */ char buf[]; }; -struct __attribute__ ((__packed__)) sdshdr8 { - uint8_t len; /* used */ - uint8_t alloc; /* excluding the header and null terminator */ +struct __attribute__((__packed__)) sdshdr8 { + uint8_t len; /* used */ + uint8_t alloc; /* excluding the header and null terminator */ unsigned char flags; /* 3 lsb of type, 5 unused bits */ char buf[]; }; -struct __attribute__ ((__packed__)) sdshdr16 { - uint16_t len; /* used */ - uint16_t alloc; /* excluding the header and null terminator */ +struct __attribute__((__packed__)) sdshdr16 { + uint16_t len; /* used */ + uint16_t alloc; /* excluding the header and null terminator */ unsigned char flags; /* 3 lsb of type, 5 unused bits */ char buf[]; }; -struct __attribute__ ((__packed__)) sdshdr32 { - uint32_t len; /* used */ - uint32_t alloc; /* excluding the header and null terminator */ +struct __attribute__((__packed__)) sdshdr32 { + uint32_t len; /* used */ + uint32_t alloc; /* excluding the header and null terminator */ unsigned char flags; /* 3 lsb of type, 5 unused bits */ char buf[]; }; -struct __attribute__ ((__packed__)) sdshdr64 { - uint64_t len; /* used */ - uint64_t alloc; /* excluding the header and null terminator */ +struct __attribute__((__packed__)) sdshdr64 { + uint64_t len; /* used */ + uint64_t alloc; /* excluding the header and null terminator */ unsigned char flags; /* 3 lsb of type, 5 unused bits */ char buf[]; }; -#define SDS_TYPE_5 0 -#define SDS_TYPE_8 1 +#define SDS_TYPE_5 0 +#define SDS_TYPE_8 1 #define SDS_TYPE_16 2 #define SDS_TYPE_32 3 #define SDS_TYPE_64 4 #define SDS_TYPE_MASK 7 #define SDS_TYPE_BITS 3 -#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))); -#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T)))) -#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS) +#define SDS_HDR_VAR(T, s) struct sdshdr##T *sh = (struct sdshdr##T *)((s) - (sizeof(struct sdshdr##T))); +#define SDS_HDR(T, s) ((struct sdshdr##T *)((s) - (sizeof(struct sdshdr##T)))) +#define SDS_TYPE_5_LEN(f) ((f) >> SDS_TYPE_BITS) static inline size_t sdslen(const sds s) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return SDS_TYPE_5_LEN(flags); - case SDS_TYPE_8: - return SDS_HDR(8,s)->len; - case SDS_TYPE_16: - return SDS_HDR(16,s)->len; - case SDS_TYPE_32: - return SDS_HDR(32,s)->len; - case SDS_TYPE_64: - return SDS_HDR(64,s)->len; + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: + return SDS_TYPE_5_LEN(flags); + case SDS_TYPE_8: + return SDS_HDR(8, s)->len; + case SDS_TYPE_16: + return SDS_HDR(16, s)->len; + case SDS_TYPE_32: + return SDS_HDR(32, s)->len; + case SDS_TYPE_64: + return SDS_HDR(64, s)->len; } return 0; } static inline size_t sdsavail(const sds s) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: { - return 0; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - return sh->alloc - sh->len; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - return sh->alloc - sh->len; - } + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: { + return 0; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8, s); + return sh->alloc - sh->len; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16, s); + return sh->alloc - sh->len; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32, s); + return sh->alloc - sh->len; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64, s); + return sh->alloc - sh->len; + } } return 0; } static inline void sdssetlen(sds s, size_t newlen) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - { - unsigned char *fp = ((unsigned char*)s)-1; - *fp = (unsigned char)(SDS_TYPE_5 | (newlen << SDS_TYPE_BITS)); - } - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->len = (uint8_t)newlen; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->len = (uint16_t)newlen; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->len = (uint32_t)newlen; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->len = (uint64_t)newlen; - break; + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: { + unsigned char *fp = ((unsigned char *)s) - 1; + *fp = (unsigned char)(SDS_TYPE_5 | (newlen << SDS_TYPE_BITS)); + } break; + case SDS_TYPE_8: + SDS_HDR(8, s)->len = (uint8_t)newlen; + break; + case SDS_TYPE_16: + SDS_HDR(16, s)->len = (uint16_t)newlen; + break; + case SDS_TYPE_32: + SDS_HDR(32, s)->len = (uint32_t)newlen; + break; + case SDS_TYPE_64: + SDS_HDR(64, s)->len = (uint64_t)newlen; + break; } } static inline void sdsinclen(sds s, size_t inc) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - { - unsigned char *fp = ((unsigned char*)s)-1; - unsigned char newlen = SDS_TYPE_5_LEN(flags)+(unsigned char)inc; - *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); - } - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->len += (uint8_t)inc; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->len += (uint16_t)inc; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->len += (uint32_t)inc; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->len += (uint64_t)inc; - break; + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: { + unsigned char *fp = ((unsigned char *)s) - 1; + unsigned char newlen = SDS_TYPE_5_LEN(flags) + (unsigned char)inc; + *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); + } break; + case SDS_TYPE_8: + SDS_HDR(8, s)->len += (uint8_t)inc; + break; + case SDS_TYPE_16: + SDS_HDR(16, s)->len += (uint16_t)inc; + break; + case SDS_TYPE_32: + SDS_HDR(32, s)->len += (uint32_t)inc; + break; + case SDS_TYPE_64: + SDS_HDR(64, s)->len += (uint64_t)inc; + break; } } /* sdsalloc() = sdsavail() + sdslen() */ static inline size_t sdsalloc(const sds s) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return SDS_TYPE_5_LEN(flags); - case SDS_TYPE_8: - return SDS_HDR(8,s)->alloc; - case SDS_TYPE_16: - return SDS_HDR(16,s)->alloc; - case SDS_TYPE_32: - return SDS_HDR(32,s)->alloc; - case SDS_TYPE_64: - return SDS_HDR(64,s)->alloc; + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: + return SDS_TYPE_5_LEN(flags); + case SDS_TYPE_8: + return SDS_HDR(8, s)->alloc; + case SDS_TYPE_16: + return SDS_HDR(16, s)->alloc; + case SDS_TYPE_32: + return SDS_HDR(32, s)->alloc; + case SDS_TYPE_64: + return SDS_HDR(64, s)->alloc; } return 0; } static inline void sdssetalloc(sds s, size_t newlen) { unsigned char flags = s[-1]; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: - /* Nothing to do, this type has no total allocation info. */ - break; - case SDS_TYPE_8: - SDS_HDR(8,s)->alloc = (uint8_t)newlen; - break; - case SDS_TYPE_16: - SDS_HDR(16,s)->alloc = (uint16_t)newlen; - break; - case SDS_TYPE_32: - SDS_HDR(32,s)->alloc = (uint32_t)newlen; - break; - case SDS_TYPE_64: - SDS_HDR(64,s)->alloc = (uint64_t)newlen; - break; + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: + /* Nothing to do, this type has no total allocation info. */ + break; + case SDS_TYPE_8: + SDS_HDR(8, s)->alloc = (uint8_t)newlen; + break; + case SDS_TYPE_16: + SDS_HDR(16, s)->alloc = (uint16_t)newlen; + break; + case SDS_TYPE_32: + SDS_HDR(32, s)->alloc = (uint32_t)newlen; + break; + case SDS_TYPE_64: + SDS_HDR(64, s)->alloc = (uint64_t)newlen; + break; } } diff --git a/include/valkey/sockcompat.h b/include/valkey/sockcompat.h index 18b1c6b0..b080e162 100644 --- a/include/valkey/sockcompat.h +++ b/include/valkey/sockcompat.h @@ -33,24 +33,29 @@ #ifndef _WIN32 /* For POSIX systems we use the standard BSD socket API. */ -#include -#include -#include -#include -#include -#include #include #include +#include +#include #include +#include +#include +#include +#include #else /* For Windows we use winsock. */ #undef _WIN32_WINNT #define _WIN32_WINNT 0x0600 /* To get WSAPoll etc. */ +/* Here we have to disable the include ordering because mstcpip.h contains + * a bunch of macro calls that is defined in other headers. */ +/* clang-format off */ +#include #include #include #include #include #include +/* clang-format on */ #ifdef _MSC_VER #include diff --git a/include/valkey/valkey.h b/include/valkey/valkey.h index 86d06d20..96c3224b 100644 --- a/include/valkey/valkey.h +++ b/include/valkey/valkey.h @@ -34,6 +34,7 @@ #ifndef VALKEY_H #define VALKEY_H #include "read.h" + #include /* for va_list */ #ifndef _MSC_VER #include /* for struct timeval */ @@ -42,14 +43,17 @@ struct timeval; /* forward declaration */ typedef SSIZE_T ssize_t; #endif -#include /* uintXX_t, etc */ -#include "sds.h" /* for sds */ #include "alloc.h" /* for allocation wrappers */ +#include "sds.h" /* for sds */ + +#include /* uintXX_t, etc */ #define LIBVALKEY_MAJOR 1 #define LIBVALKEY_MINOR 2 #define LIBVALKEY_PATCH 0 +/* clang-format off */ #define LIBVALKEY_SONAME 1.2.1-dev +/* clang-format on */ /* Connection type can be blocking or non-blocking and is set in the * least significant bit of the flags field in valkeyContext. */ @@ -102,16 +106,16 @@ typedef SSIZE_T ssize_t; /* number of times we retry to connect in the case of EADDRNOTAVAIL and * SO_REUSEADDR is being used. */ -#define VALKEY_CONNECT_RETRIES 10 +#define VALKEY_CONNECT_RETRIES 10 /* Forward declarations for structs defined elsewhere */ struct valkeyAsyncContext; struct valkeyContext; /* RESP3 push helpers and callback prototypes */ -#define valkeyIsPushReply(r) (((valkeyReply*)(r))->type == VALKEY_REPLY_PUSH) -typedef void (valkeyPushFn)(void *, void *); -typedef void (valkeyAsyncPushFn)(struct valkeyAsyncContext *, void *); +#define valkeyIsPushReply(r) (((valkeyReply *)(r))->type == VALKEY_REPLY_PUSH) +typedef void(valkeyPushFn)(void *, void *); +typedef void(valkeyAsyncPushFn)(struct valkeyAsyncContext *, void *); #ifdef __cplusplus extern "C" { @@ -119,16 +123,18 @@ extern "C" { /* This is the reply object returned by valkeyCommand() */ typedef struct valkeyReply { - int type; /* VALKEY_REPLY_* */ - long long integer; /* The integer when type is VALKEY_REPLY_INTEGER */ - double dval; /* The double when type is VALKEY_REPLY_DOUBLE */ - size_t len; /* Length of string */ - char *str; /* Used for VALKEY_REPLY_ERROR, VALKEY_REPLY_STRING - VALKEY_REPLY_VERB, VALKEY_REPLY_DOUBLE (in additional to dval), - and VALKEY_REPLY_BIGNUM. */ - char vtype[4]; /* Used for VALKEY_REPLY_VERB, contains the null - terminated 3 character content type, such as "txt". */ - size_t elements; /* number of elements, for VALKEY_REPLY_ARRAY */ + int type; /* VALKEY_REPLY_* */ + long long integer; /* The integer when type is VALKEY_REPLY_INTEGER */ + double dval; /* The double when type is VALKEY_REPLY_DOUBLE */ + size_t len; /* Length of string */ + char *str; /* Used for VALKEY_REPLY_ERROR, VALKEY_REPLY_STRING + * VALKEY_REPLY_VERB, + * VALKEY_REPLY_DOUBLE (in additional to dval), + * and VALKEY_REPLY_BIGNUM. */ + char vtype[4]; /* Used for VALKEY_REPLY_VERB, contains the null + * terminated 3 character content type, + * such as "txt". */ + size_t elements; /* number of elements, for VALKEY_REPLY_ARRAY */ struct valkeyReply **element; /* elements vector for VALKEY_REPLY_ARRAY */ } valkeyReply; @@ -141,7 +147,7 @@ void freeReplyObject(void *reply); int valkeyvFormatCommand(char **target, const char *format, va_list ap); int valkeyFormatCommand(char **target, const char *format, ...); long long valkeyFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen); -long long valkeyFormatSdsCommandArgv(sds *target, int argc, const char ** argv, const size_t *argvlen); +long long valkeyFormatSdsCommandArgv(sds *target, int argc, const char **argv, const size_t *argvlen); void valkeyFreeCommand(char *cmd); void valkeyFreeSdsCommand(sds cmd); @@ -181,7 +187,7 @@ typedef int valkeyFD; #ifdef _WIN64 typedef unsigned long long valkeyFD; /* SOCKET = 64-bit UINT_PTR */ #else -typedef unsigned long valkeyFD; /* SOCKET = 32-bit UINT_PTR */ +typedef unsigned long valkeyFD; /* SOCKET = 32-bit UINT_PTR */ #endif #define VALKEY_INVALID_FD ((valkeyFD)(~0)) /* INVALID_SOCKET */ #endif @@ -226,21 +232,24 @@ typedef struct { /** * Helper macros to initialize options to their specified fields. */ -#define VALKEY_OPTIONS_SET_TCP(opts, ip_, port_) do { \ - (opts)->type = VALKEY_CONN_TCP; \ - (opts)->endpoint.tcp.ip = ip_; \ - (opts)->endpoint.tcp.port = port_; \ - } while(0) - -#define VALKEY_OPTIONS_SET_UNIX(opts, path) do { \ - (opts)->type = VALKEY_CONN_UNIX; \ - (opts)->endpoint.unix_socket = path; \ - } while(0) - -#define VALKEY_OPTIONS_SET_PRIVDATA(opts, data, dtor) do { \ - (opts)->privdata = data; \ - (opts)->free_privdata = dtor; \ - } while(0) +#define VALKEY_OPTIONS_SET_TCP(opts, ip_, port_) \ + do { \ + (opts)->type = VALKEY_CONN_TCP; \ + (opts)->endpoint.tcp.ip = ip_; \ + (opts)->endpoint.tcp.port = port_; \ + } while (0) + +#define VALKEY_OPTIONS_SET_UNIX(opts, path) \ + do { \ + (opts)->type = VALKEY_CONN_UNIX; \ + (opts)->endpoint.unix_socket = path; \ + } while (0) + +#define VALKEY_OPTIONS_SET_PRIVDATA(opts, data, dtor) \ + do { \ + (opts)->privdata = data; \ + (opts)->free_privdata = dtor; \ + } while (0) typedef struct valkeyContextFuncs { int (*connect)(struct valkeyContext *, const valkeyOptions *); @@ -258,16 +267,15 @@ typedef struct valkeyContextFuncs { int (*set_timeout)(struct valkeyContext *, const struct timeval); } valkeyContextFuncs; - /* Context for a connection to Valkey */ typedef struct valkeyContext { - const valkeyContextFuncs *funcs; /* Function table */ + const valkeyContextFuncs *funcs; /* Function table */ - int err; /* Error flags, 0 when there is no error */ + int err; /* Error flags, 0 when there is no error */ char errstr[128]; /* String representation of error when applicable */ valkeyFD fd; int flags; - char *obuf; /* Write buffer */ + char *obuf; /* Write buffer */ valkeyReader *reader; /* Protocol reader */ enum valkeyConnectionType connection_type; @@ -306,9 +314,9 @@ valkeyContext *valkeyConnect(const char *ip, int port); valkeyContext *valkeyConnectWithTimeout(const char *ip, int port, const struct timeval tv); valkeyContext *valkeyConnectNonBlock(const char *ip, int port); valkeyContext *valkeyConnectBindNonBlock(const char *ip, int port, - const char *source_addr); + const char *source_addr); valkeyContext *valkeyConnectBindNonBlockWithReuse(const char *ip, int port, - const char *source_addr); + const char *source_addr); valkeyContext *valkeyConnectUnix(const char *path); valkeyContext *valkeyConnectUnixWithTimeout(const char *path, const struct timeval tv); valkeyContext *valkeyConnectUnixNonBlock(const char *path); diff --git a/include/valkey/valkey_rdma.h b/include/valkey/valkey_rdma.h index 3e6fa220..7308288a 100644 --- a/include/valkey/valkey_rdma.h +++ b/include/valkey/valkey_rdma.h @@ -44,12 +44,12 @@ extern "C" { * Helper macros to initialize options for RDMA. * It's ok to reuse TCP options. */ -#define VALKEY_OPTIONS_SET_RDMA(opts, ip_, port_) do { \ - (opts)->type = VALKEY_CONN_RDMA; \ - (opts)->endpoint.tcp.ip = ip_; \ - (opts)->endpoint.tcp.port = port_; \ - } while(0) - +#define VALKEY_OPTIONS_SET_RDMA(opts, ip_, port_) \ + do { \ + (opts)->type = VALKEY_CONN_RDMA; \ + (opts)->endpoint.tcp.ip = ip_; \ + (opts)->endpoint.tcp.port = port_; \ + } while (0) int valkeyInitiateRdma(void); @@ -57,4 +57,4 @@ int valkeyInitiateRdma(void); } #endif -#endif /* VALKEY_RDMA_H */ +#endif /* VALKEY_RDMA_H */ diff --git a/include/valkey/valkey_ssl.h b/include/valkey/valkey_ssl.h index 50a951d0..c7a644a4 100644 --- a/include/valkey/valkey_ssl.h +++ b/include/valkey/valkey_ssl.h @@ -51,15 +51,15 @@ typedef struct valkeySSLContext valkeySSLContext; */ typedef enum { - VALKEY_SSL_CTX_NONE = 0, /* No Error */ - VALKEY_SSL_CTX_CREATE_FAILED, /* Failed to create OpenSSL SSL_CTX */ - VALKEY_SSL_CTX_CERT_KEY_REQUIRED, /* Client cert and key must both be specified or skipped */ - VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED, /* Failed to load CA Certificate or CA Path */ - VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED, /* Failed to load client certificate */ - VALKEY_SSL_CTX_CLIENT_DEFAULT_CERT_FAILED, /* Failed to set client default certificate directory */ - VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED, /* Failed to load private key */ - VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED, /* Failed to open system certificate store */ - VALKEY_SSL_CTX_OS_CERT_ADD_FAILED /* Failed to add CA certificates obtained from system to the SSL context */ + VALKEY_SSL_CTX_NONE = 0, /* No Error */ + VALKEY_SSL_CTX_CREATE_FAILED, /* Failed to create OpenSSL SSL_CTX */ + VALKEY_SSL_CTX_CERT_KEY_REQUIRED, /* Client cert and key must both be specified or skipped */ + VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED, /* Failed to load CA Certificate or CA Path */ + VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED, /* Failed to load client certificate */ + VALKEY_SSL_CTX_CLIENT_DEFAULT_CERT_FAILED, /* Failed to set client default certificate directory */ + VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED, /* Failed to load private key */ + VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED, /* Failed to open system certificate store */ + VALKEY_SSL_CTX_OS_CERT_ADD_FAILED /* Failed to add CA certificates obtained from system to the SSL context */ } valkeySSLContextError; /* Constants that mirror OpenSSL's verify modes. By default, @@ -120,8 +120,8 @@ int valkeyInitOpenSSL(void); */ valkeySSLContext *valkeyCreateSSLContext(const char *cacert_filename, const char *capath, - const char *cert_filename, const char *private_key_filename, - const char *server_name, valkeySSLContextError *error); + const char *cert_filename, const char *private_key_filename, + const char *server_name, valkeySSLContextError *error); /** * Helper function to initialize an OpenSSL context that can be used @@ -133,7 +133,7 @@ valkeySSLContext *valkeyCreateSSLContext(const char *cacert_filename, const char * (returning a NULL). */ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, - valkeySSLContextError *error); + valkeySSLContextError *error); /** * Free a previously created OpenSSL context. @@ -160,4 +160,4 @@ int valkeyInitiateSSL(valkeyContext *c, struct ssl_st *ssl); } #endif -#endif /* VALKEY_SSL_H */ +#endif /* VALKEY_SSL_H */ diff --git a/include/valkey/valkeycluster.h b/include/valkey/valkeycluster.h index 0f5ca950..b87c4528 100644 --- a/include/valkey/valkeycluster.h +++ b/include/valkey/valkeycluster.h @@ -113,8 +113,8 @@ typedef struct valkeyClusterContext { char *username; /* Authenticate using user */ char *password; /* Authentication password */ - struct dict *nodes; /* Known valkeyClusterNode's */ - uint64_t route_version; /* Increased when the node lookup table changes */ + struct dict *nodes; /* Known valkeyClusterNode's */ + uint64_t route_version; /* Increased when the node lookup table changes */ valkeyClusterNode **table; /* valkeyClusterNode lookup table */ struct hilist *requests; /* Outstanding commands (Pipelining) */ @@ -122,7 +122,7 @@ typedef struct valkeyClusterContext { int retry_count; /* Current number of failing attempts */ int need_update_route; /* Indicator for valkeyClusterReset() (Pipel.) */ - void *ssl; /* Pointer to a valkeySSLContext when using SSL/TLS. */ + void *ssl; /* Pointer to a valkeySSLContext when using SSL/TLS. */ sslInitFn *ssl_init_fn; /* Func ptr for SSL context initiation */ void (*on_connect)(const struct valkeyContext *c, int status); diff --git a/include/valkey/valkeycluster_ssl.h b/include/valkey/valkeycluster_ssl.h index 06e9f8f8..9ddb4b24 100644 --- a/include/valkey/valkeycluster_ssl.h +++ b/include/valkey/valkeycluster_ssl.h @@ -29,8 +29,9 @@ #ifndef VALKEYCLUSTER_SSL_H #define VALKEYCLUSTER_SSL_H -#include "valkeycluster.h" +#include "valkey.h" #include "valkey_ssl.h" +#include "valkeycluster.h" #ifdef __cplusplus extern "C" { diff --git a/src/adlist.c b/src/adlist.c index 2903a007..3d2f5ac3 100644 --- a/src/adlist.c +++ b/src/adlist.c @@ -27,12 +27,13 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "adlist.h" #include "alloc.h" -#include "adlist.h" #include "vkutil.h" +#include + /* Create a new list. The created list can be freed with * AlFreeList(), but private value of every node need to be freed * by the user before to call AlFreeList(). diff --git a/src/alloc.c b/src/alloc.c index dd50c691..91f8bdf7 100644 --- a/src/alloc.c +++ b/src/alloc.c @@ -29,9 +29,11 @@ */ #include "fmacros.h" + #include "alloc.h" -#include + #include +#include valkeyAllocFuncs valkeyAllocFns = { .mallocFn = malloc, @@ -52,7 +54,7 @@ valkeyAllocFuncs valkeySetAllocators(valkeyAllocFuncs *override) { /* Reset allocators to use libc defaults */ void valkeyResetAllocators(void) { - valkeyAllocFns = (valkeyAllocFuncs) { + valkeyAllocFns = (valkeyAllocFuncs){ .mallocFn = malloc, .callocFn = calloc, .reallocFn = realloc, diff --git a/src/async.c b/src/async.c index 9277e947..f920be3a 100644 --- a/src/async.c +++ b/src/async.c @@ -30,24 +30,27 @@ */ #include "fmacros.h" + #include "alloc.h" + #include #include #ifndef _MSC_VER #include #endif -#include -#include -#include -#include "async.h" -#include "net.h" -#include "dict.h" -#include "sds.h" #include "win32.h" +#include "async.h" #include "async_private.h" +#include "dict.h" +#include "net.h" +#include "sds.h" #include "valkey_private.h" +#include +#include +#include + #ifdef NDEBUG #undef assert #define assert(e) (void)(e) @@ -63,34 +66,35 @@ static unsigned int callbackHash(const void *key) { } static void *callbackValDup(void *privdata, const void *src) { - ((void) privdata); + ((void)privdata); valkeyCallback *dup; dup = vk_malloc(sizeof(*dup)); if (dup == NULL) return NULL; - memcpy(dup,src,sizeof(*dup)); + memcpy(dup, src, sizeof(*dup)); return dup; } static int callbackKeyCompare(void *privdata, const void *key1, const void *key2) { int l1, l2; - ((void) privdata); + ((void)privdata); l1 = sdslen((const sds)key1); l2 = sdslen((const sds)key2); - if (l1 != l2) return 0; - return memcmp(key1,key2,l1) == 0; + if (l1 != l2) + return 0; + return memcmp(key1, key2, l1) == 0; } static void callbackKeyDestructor(void *privdata, void *key) { - ((void) privdata); + ((void)privdata); sdsfree((sds)key); } static void callbackValDestructor(void *privdata, void *val) { - ((void) privdata); + ((void)privdata); vk_free(val); } @@ -100,22 +104,21 @@ static dictType callbackDict = { callbackValDup, callbackKeyCompare, callbackKeyDestructor, - callbackValDestructor -}; + callbackValDestructor}; static valkeyAsyncContext *valkeyAsyncInitialize(valkeyContext *c) { valkeyAsyncContext *ac; dict *channels = NULL, *patterns = NULL; - channels = dictCreate(&callbackDict,NULL); + channels = dictCreate(&callbackDict, NULL); if (channels == NULL) goto oom; - patterns = dictCreate(&callbackDict,NULL); + patterns = dictCreate(&callbackDict, NULL); if (patterns == NULL) goto oom; - ac = vk_realloc(c,sizeof(valkeyAsyncContext)); + ac = vk_realloc(c, sizeof(valkeyAsyncContext)); if (ac == NULL) goto oom; @@ -153,8 +156,10 @@ static valkeyAsyncContext *valkeyAsyncInitialize(valkeyContext *c) { return ac; oom: - if (channels) dictRelease(channels); - if (patterns) dictRelease(patterns); + if (channels) + dictRelease(channels); + if (patterns) + dictRelease(patterns); return NULL; } @@ -229,8 +234,7 @@ valkeyAsyncContext *valkeyAsyncConnectUnix(const char *path) { static int valkeyAsyncSetConnectCallbackImpl(valkeyAsyncContext *ac, valkeyConnectCallback *fn, - valkeyConnectCallbackNC *fn_nc) -{ + valkeyConnectCallbackNC *fn_nc) { /* If either are already set, this is an error */ if (ac->onConnect || ac->onConnectNC) return VALKEY_ERR; @@ -275,7 +279,7 @@ static int valkeyPushCallback(valkeyCallbackList *list, valkeyCallback *source) return VALKEY_ERR_OOM; if (source != NULL) { - memcpy(cb,source,sizeof(*cb)); + memcpy(cb, source, sizeof(*cb)); cb->next = NULL; } @@ -297,7 +301,7 @@ static int valkeyShiftCallback(valkeyCallbackList *list, valkeyCallback *target) /* Copy callback from heap to stack */ if (target != NULL) - memcpy(target,cb,sizeof(*cb)); + memcpy(target, cb, sizeof(*cb)); vk_free(cb); return VALKEY_OK; } @@ -308,7 +312,7 @@ static void valkeyRunCallback(valkeyAsyncContext *ac, valkeyCallback *cb, valkey valkeyContext *c = &(ac->c); if (cb->fn != NULL) { c->flags |= VALKEY_IN_CALLBACK; - cb->fn(ac,reply,cb->privdata); + cb->fn(ac, reply, cb->privdata); c->flags &= ~VALKEY_IN_CALLBACK; } } @@ -321,8 +325,7 @@ static void valkeyRunPushCallback(valkeyAsyncContext *ac, valkeyReply *reply) { } } -static void valkeyRunConnectCallback(valkeyAsyncContext *ac, int status) -{ +static void valkeyRunConnectCallback(valkeyAsyncContext *ac, int status) { if (ac->onConnect == NULL && ac->onConnectNC == NULL) return; @@ -344,8 +347,7 @@ static void valkeyRunConnectCallback(valkeyAsyncContext *ac, int status) } } -static void valkeyRunDisconnectCallback(valkeyAsyncContext *ac, int status) -{ +static void valkeyRunDisconnectCallback(valkeyAsyncContext *ac, int status) { if (ac->onDisconnect) { if (!(ac->c.flags & VALKEY_IN_CALLBACK)) { ac->c.flags |= VALKEY_IN_CALLBACK; @@ -366,24 +368,24 @@ static void valkeyAsyncFreeInternal(valkeyAsyncContext *ac) { dictEntry *de; /* Execute pending callbacks with NULL reply. */ - while (valkeyShiftCallback(&ac->replies,&cb) == VALKEY_OK) - valkeyRunCallback(ac,&cb,NULL); - while (valkeyShiftCallback(&ac->sub.replies,&cb) == VALKEY_OK) - valkeyRunCallback(ac,&cb,NULL); + while (valkeyShiftCallback(&ac->replies, &cb) == VALKEY_OK) + valkeyRunCallback(ac, &cb, NULL); + while (valkeyShiftCallback(&ac->sub.replies, &cb) == VALKEY_OK) + valkeyRunCallback(ac, &cb, NULL); /* Run subscription callbacks with NULL reply */ if (ac->sub.channels) { - dictInitIterator(&it,ac->sub.channels); + dictInitIterator(&it, ac->sub.channels); while ((de = dictNext(&it)) != NULL) - valkeyRunCallback(ac,dictGetEntryVal(de),NULL); + valkeyRunCallback(ac, dictGetEntryVal(de), NULL); dictRelease(ac->sub.channels); } if (ac->sub.patterns) { - dictInitIterator(&it,ac->sub.patterns); + dictInitIterator(&it, ac->sub.patterns); while ((de = dictNext(&it)) != NULL) - valkeyRunCallback(ac,dictGetEntryVal(de),NULL); + valkeyRunCallback(ac, dictGetEntryVal(de), NULL); dictRelease(ac->sub.patterns); } @@ -432,7 +434,7 @@ void valkeyAsyncDisconnectInternal(valkeyAsyncContext *ac) { if (ac->err == 0) { /* For clean disconnects, there should be no pending callbacks. */ - int ret = valkeyShiftCallback(&ac->replies,NULL); + int ret = valkeyShiftCallback(&ac->replies, NULL); assert(ret == VALKEY_ERR); } else { /* Disconnection is caused by an error, make sure that pending @@ -447,7 +449,7 @@ void valkeyAsyncDisconnectInternal(valkeyAsyncContext *ac) { /* For non-clean disconnects, valkeyAsyncFreeInternal() will execute pending * callbacks with a NULL-reply. */ if (!(c->flags & VALKEY_NO_AUTO_FREE)) { - valkeyAsyncFreeInternal(ac); + valkeyAsyncFreeInternal(ac); } } @@ -492,25 +494,26 @@ static int valkeyGetSubscribeCallback(valkeyAsyncContext *ac, valkeyReply *reply /* Locate the right callback */ if (reply->element[1]->type == VALKEY_REPLY_STRING) { - sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len); - if (sname == NULL) goto oom; + sname = sdsnewlen(reply->element[1]->str, reply->element[1]->len); + if (sname == NULL) + goto oom; - if ((de = dictFind(callbacks,sname)) != NULL) { + if ((de = dictFind(callbacks, sname)) != NULL) { cb = dictGetEntryVal(de); - memcpy(dstcb,cb,sizeof(*dstcb)); + memcpy(dstcb, cb, sizeof(*dstcb)); } } /* If this is an subscribe reply decrease pending counter. */ - if (strcasecmp(stype+pvariant,"subscribe") == 0) { + if (strcasecmp(stype + pvariant, "subscribe") == 0) { assert(cb != NULL); cb->pending_subs -= 1; - } else if (strcasecmp(stype+pvariant,"unsubscribe") == 0) { + } else if (strcasecmp(stype + pvariant, "unsubscribe") == 0) { if (cb == NULL) ac->sub.pending_unsubs -= 1; else if (cb->pending_subs == 0) - dictDelete(callbacks,sname); + dictDelete(callbacks, sname); /* If this was the last unsubscribe message, revert to * non-subscribe mode. */ @@ -518,23 +521,23 @@ static int valkeyGetSubscribeCallback(valkeyAsyncContext *ac, valkeyReply *reply /* Unset subscribed flag only when no pipelined pending subscribe * or pending unsubscribe replies. */ - if (reply->element[2]->integer == 0 - && dictSize(ac->sub.channels) == 0 - && dictSize(ac->sub.patterns) == 0 - && ac->sub.pending_unsubs == 0) { + if (reply->element[2]->integer == 0 && + dictSize(ac->sub.channels) == 0 && + dictSize(ac->sub.patterns) == 0 && + ac->sub.pending_unsubs == 0) { c->flags &= ~VALKEY_SUBSCRIBED; /* Move ongoing regular command callbacks. */ valkeyCallback cb; - while (valkeyShiftCallback(&ac->sub.replies,&cb) == VALKEY_OK) { - valkeyPushCallback(&ac->replies,&cb); + while (valkeyShiftCallback(&ac->sub.replies, &cb) == VALKEY_OK) { + valkeyPushCallback(&ac->replies, &cb); } } } sdsfree(sname); } else { /* Shift callback for pending command in subscribed context. */ - valkeyShiftCallback(&ac->sub.replies,dstcb); + valkeyShiftCallback(&ac->sub.replies, dstcb); } return VALKEY_OK; oom: @@ -552,8 +555,7 @@ static int valkeyIsSubscribeReply(valkeyReply *reply) { /* We will always have at least one string with the subscribe/message type */ if (reply->elements < 1 || reply->element[0]->type != VALKEY_REPLY_STRING || - reply->element[0]->len < sizeof("message") - 1) - { + reply->element[0]->len < sizeof("message") - 1) { return 0; } @@ -572,12 +574,11 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { void *reply = NULL; int status; - while((status = valkeyGetReply(c,&reply)) == VALKEY_OK) { + while ((status = valkeyGetReply(c, &reply)) == VALKEY_OK) { if (reply == NULL) { /* When the connection is being disconnected and there are * no more replies, this is the cue to really disconnect. */ - if (c->flags & VALKEY_DISCONNECTING && sdslen(c->obuf) == 0 - && ac->replies.head == NULL) { + if (c->flags & VALKEY_DISCONNECTING && sdslen(c->obuf) == 0 && ac->replies.head == NULL) { valkeyAsyncDisconnectInternal(ac); return; } @@ -587,7 +588,8 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { } /* Keep track of push message support for subscribe handling */ - if (valkeyIsPushReply(reply)) c->flags |= VALKEY_SUPPORTS_PUSH; + if (valkeyIsPushReply(reply)) + c->flags |= VALKEY_SUPPORTS_PUSH; /* Send any non-subscribe related PUSH messages to our PUSH handler * while allowing subscribe related PUSH messages to pass through. @@ -602,7 +604,7 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { /* Even if the context is subscribed, pending regular * callbacks will get a reply before pub/sub messages arrive. */ valkeyCallback cb = {NULL, NULL, 0, 0, NULL}; - if (valkeyShiftCallback(&ac->replies,&cb) != VALKEY_OK) { + if (valkeyShiftCallback(&ac->replies, &cb) != VALKEY_OK) { /* * A spontaneous reply in a not-subscribed context can be the error * reply that is sent when a new connection exceeds the maximum @@ -618,9 +620,9 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { * In this case we also want to close the connection, and have the * user wait until the server is ready to take our request. */ - if (((valkeyReply*)reply)->type == VALKEY_REPLY_ERROR) { + if (((valkeyReply *)reply)->type == VALKEY_REPLY_ERROR) { c->err = VALKEY_ERR_OTHER; - snprintf(c->errstr,sizeof(c->errstr),"%s",((valkeyReply*)reply)->str); + snprintf(c->errstr, sizeof(c->errstr), "%s", ((valkeyReply *)reply)->str); c->reader->fn->freeObject(reply); valkeyAsyncDisconnectInternal(ac); return; @@ -628,12 +630,12 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { /* No more regular callbacks and no errors, the context *must* be subscribed. */ assert(c->flags & VALKEY_SUBSCRIBED); if (c->flags & VALKEY_SUBSCRIBED) - valkeyGetSubscribeCallback(ac,reply,&cb); + valkeyGetSubscribeCallback(ac, reply, &cb); } if (cb.fn != NULL) { - valkeyRunCallback(ac,&cb,reply); - if (!(c->flags & VALKEY_NO_AUTO_FREE_REPLIES)){ + valkeyRunCallback(ac, &cb, reply); + if (!(c->flags & VALKEY_NO_AUTO_FREE_REPLIES)) { c->reader->fn->freeObject(reply); } @@ -652,7 +654,7 @@ void valkeyProcessCallbacks(valkeyAsyncContext *ac) { /* If in monitor mode, repush the callback */ if (c->flags & VALKEY_MONITORING) { - valkeyPushCallback(&ac->replies,&cb); + valkeyPushCallback(&ac->replies, &cb); } } @@ -742,7 +744,7 @@ void valkeyAsyncWrite(valkeyAsyncContext *ac) { valkeyContext *c = &(ac->c); int done = 0; - if (valkeyBufferWrite(c,&done) == VALKEY_ERR) { + if (valkeyBufferWrite(c, &done) == VALKEY_ERR) { valkeyAsyncDisconnectInternal(ac); } else { /* Continue writing when not done, stop writing otherwise */ @@ -817,15 +819,16 @@ void valkeyAsyncHandleTimeout(valkeyAsyncContext *ac) { static const char *nextArgument(const char *start, const char **str, size_t *len) { const char *p = start; if (p[0] != '$') { - p = strchr(p,'$'); - if (p == NULL) return NULL; + p = strchr(p, '$'); + if (p == NULL) + return NULL; } - *len = (int)strtol(p+1,NULL,10); - p = strchr(p,'\r'); + *len = (int)strtol(p + 1, NULL, 10); + p = strchr(p, '\r'); assert(p); - *str = p+2; - return p+2+(*len)+2; + *str = p + 2; + return p + 2 + (*len) + 2; } /* Helper function for the valkeyAsyncCommand* family of functions. Writes a @@ -846,7 +849,8 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, int ret; /* Don't accept new commands when the connection is about to be closed. */ - if (c->flags & (VALKEY_DISCONNECTING | VALKEY_FREEING)) return VALKEY_ERR; + if (c->flags & (VALKEY_DISCONNECTING | VALKEY_FREEING)) + return VALKEY_ERR; /* Setup callback */ cb.fn = fn; @@ -855,19 +859,19 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, cb.unsubscribe_sent = 0; /* Find out which command will be appended. */ - p = nextArgument(cmd,&cstr,&clen); + p = nextArgument(cmd, &cstr, &clen); assert(p != NULL); hasnext = (p[0] == '$'); pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0; cstr += pvariant; clen -= pvariant; - if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) { + if (hasnext && strncasecmp(cstr, "subscribe\r\n", 11) == 0) { c->flags |= VALKEY_SUBSCRIBED; /* Add every channel/pattern to the list of subscription callbacks. */ - while ((p = nextArgument(p,&astr,&alen)) != NULL) { - sname = sdsnewlen(astr,alen); + while ((p = nextArgument(p, &astr, &alen)) != NULL) { + sname = sdsnewlen(astr, alen); if (sname == NULL) goto oom; @@ -876,21 +880,23 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, else cbdict = ac->sub.channels; - de = dictFind(cbdict,sname); + de = dictFind(cbdict, sname); if (de != NULL) { existcb = dictGetEntryVal(de); cb.pending_subs = existcb->pending_subs + 1; } - ret = dictReplace(cbdict,sname,&cb); + ret = dictReplace(cbdict, sname, &cb); - if (ret == 0) sdsfree(sname); + if (ret == 0) + sdsfree(sname); } - } else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) { + } else if (strncasecmp(cstr, "unsubscribe\r\n", 13) == 0) { /* It is only useful to call (P)UNSUBSCRIBE when the context is * subscribed to one or more channels or patterns. */ - if (!(c->flags & VALKEY_SUBSCRIBED)) return VALKEY_ERR; + if (!(c->flags & VALKEY_SUBSCRIBED)) + return VALKEY_ERR; if (pvariant) cbdict = ac->sub.patterns; @@ -900,12 +906,12 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, if (hasnext) { /* Send an unsubscribe with specific channels/patterns. * Bookkeeping the number of expected replies */ - while ((p = nextArgument(p,&astr,&alen)) != NULL) { - sname = sdsnewlen(astr,alen); + while ((p = nextArgument(p, &astr, &alen)) != NULL) { + sname = sdsnewlen(astr, alen); if (sname == NULL) goto oom; - de = dictFind(cbdict,sname); + de = dictFind(cbdict, sname); if (de != NULL) { existcb = dictGetEntryVal(de); if (existcb->unsubscribe_sent == 0) @@ -923,7 +929,7 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, /* Send an unsubscribe without specific channels/patterns. * Bookkeeping the number of expected replies */ int no_subs = 1; - dictInitIterator(&it,cbdict); + dictInitIterator(&it, cbdict); while ((de = dictNext(&it)) != NULL) { existcb = dictGetEntryVal(de); if (existcb->unsubscribe_sent == 0) { @@ -940,22 +946,22 @@ static int valkeyAsyncAppendCmdLen(valkeyAsyncContext *ac, valkeyCallbackFn *fn, /* (P)UNSUBSCRIBE does not have its own response: every channel or * pattern that is unsubscribed will receive a message. This means we * should not append a callback function for this command. */ - } else if (strncasecmp(cstr,"monitor\r\n",9) == 0) { + } else if (strncasecmp(cstr, "monitor\r\n", 9) == 0) { /* Set monitor flag and push callback */ c->flags |= VALKEY_MONITORING; - if (valkeyPushCallback(&ac->replies,&cb) != VALKEY_OK) + if (valkeyPushCallback(&ac->replies, &cb) != VALKEY_OK) goto oom; } else { if (c->flags & VALKEY_SUBSCRIBED) { - if (valkeyPushCallback(&ac->sub.replies,&cb) != VALKEY_OK) + if (valkeyPushCallback(&ac->sub.replies, &cb) != VALKEY_OK) goto oom; } else { - if (valkeyPushCallback(&ac->replies,&cb) != VALKEY_OK) + if (valkeyPushCallback(&ac->replies, &cb) != VALKEY_OK) goto oom; } } - valkeyAppendCmdLen(c,cmd,len); + valkeyAppendCmdLen(c, cmd, len); /* Always schedule a write when the write buffer is non-empty */ _EL_ADD_WRITE(ac); @@ -971,13 +977,13 @@ int valkeyvAsyncCommand(valkeyAsyncContext *ac, valkeyCallbackFn *fn, void *priv char *cmd; int len; int status; - len = valkeyvFormatCommand(&cmd,format,ap); + len = valkeyvFormatCommand(&cmd, format, ap); /* We don't want to pass -1 or -2 to future functions as a length. */ if (len < 0) return VALKEY_ERR; - status = valkeyAsyncAppendCmdLen(ac,fn,privdata,cmd,len); + status = valkeyAsyncAppendCmdLen(ac, fn, privdata, cmd, len); vk_free(cmd); return status; } @@ -985,8 +991,8 @@ int valkeyvAsyncCommand(valkeyAsyncContext *ac, valkeyCallbackFn *fn, void *priv int valkeyAsyncCommand(valkeyAsyncContext *ac, valkeyCallbackFn *fn, void *privdata, const char *format, ...) { va_list ap; int status; - va_start(ap,format); - status = valkeyvAsyncCommand(ac,fn,privdata,format,ap); + va_start(ap, format); + status = valkeyvAsyncCommand(ac, fn, privdata, format, ap); va_end(ap); return status; } @@ -995,16 +1001,16 @@ int valkeyAsyncCommandArgv(valkeyAsyncContext *ac, valkeyCallbackFn *fn, void *p sds cmd; long long len; int status; - len = valkeyFormatSdsCommandArgv(&cmd,argc,argv,argvlen); + len = valkeyFormatSdsCommandArgv(&cmd, argc, argv, argvlen); if (len < 0) return VALKEY_ERR; - status = valkeyAsyncAppendCmdLen(ac,fn,privdata,cmd,len); + status = valkeyAsyncAppendCmdLen(ac, fn, privdata, cmd, len); sdsfree(cmd); return status; } int valkeyAsyncFormattedCommand(valkeyAsyncContext *ac, valkeyCallbackFn *fn, void *privdata, const char *cmd, size_t len) { - int status = valkeyAsyncAppendCmdLen(ac,fn,privdata,cmd,len); + int status = valkeyAsyncAppendCmdLen(ac, fn, privdata, cmd, len); return status; } @@ -1025,8 +1031,7 @@ int valkeyAsyncSetTimeout(valkeyAsyncContext *ac, struct timeval tv) { } if (tv.tv_sec != ac->c.command_timeout->tv_sec || - tv.tv_usec != ac->c.command_timeout->tv_usec) - { + tv.tv_usec != ac->c.command_timeout->tv_usec) { *ac->c.command_timeout = tv; } diff --git a/src/async_private.h b/src/async_private.h index 21b6de03..60cad383 100644 --- a/src/async_private.h +++ b/src/async_private.h @@ -32,35 +32,43 @@ #ifndef VALKEY_ASYNC_PRIVATE_H #define VALKEY_ASYNC_PRIVATE_H -#define _EL_ADD_READ(ctx) \ - do { \ - refreshTimeout(ctx); \ - if ((ctx)->ev.addRead) (ctx)->ev.addRead((ctx)->ev.data); \ +#define _EL_ADD_READ(ctx) \ + do { \ + refreshTimeout(ctx); \ + if ((ctx)->ev.addRead) \ + (ctx)->ev.addRead((ctx)->ev.data); \ } while (0) -#define _EL_DEL_READ(ctx) do { \ - if ((ctx)->ev.delRead) (ctx)->ev.delRead((ctx)->ev.data); \ - } while(0) -#define _EL_ADD_WRITE(ctx) \ - do { \ - refreshTimeout(ctx); \ - if ((ctx)->ev.addWrite) (ctx)->ev.addWrite((ctx)->ev.data); \ +#define _EL_DEL_READ(ctx) \ + do { \ + if ((ctx)->ev.delRead) \ + (ctx)->ev.delRead((ctx)->ev.data); \ + } while (0) +#define _EL_ADD_WRITE(ctx) \ + do { \ + refreshTimeout(ctx); \ + if ((ctx)->ev.addWrite) \ + (ctx)->ev.addWrite((ctx)->ev.data); \ + } while (0) +#define _EL_DEL_WRITE(ctx) \ + do { \ + if ((ctx)->ev.delWrite) \ + (ctx)->ev.delWrite((ctx)->ev.data); \ + } while (0) +#define _EL_CLEANUP(ctx) \ + do { \ + if ((ctx)->ev.cleanup) \ + (ctx)->ev.cleanup((ctx)->ev.data); \ + ctx->ev.cleanup = NULL; \ } while (0) -#define _EL_DEL_WRITE(ctx) do { \ - if ((ctx)->ev.delWrite) (ctx)->ev.delWrite((ctx)->ev.data); \ - } while(0) -#define _EL_CLEANUP(ctx) do { \ - if ((ctx)->ev.cleanup) (ctx)->ev.cleanup((ctx)->ev.data); \ - ctx->ev.cleanup = NULL; \ - } while(0) static inline void refreshTimeout(valkeyAsyncContext *ctx) { - #define VALKEY_TIMER_ISSET(tvp) \ - (tvp && ((tvp)->tv_sec || (tvp)->tv_usec)) +#define VALKEY_TIMER_ISSET(tvp) \ + (tvp && ((tvp)->tv_sec || (tvp)->tv_usec)) - #define VALKEY_EL_TIMER(ac, tvp) \ - if ((ac)->ev.scheduleTimer && VALKEY_TIMER_ISSET(tvp)) { \ - (ac)->ev.scheduleTimer((ac)->ev.data, *(tvp)); \ - } +#define VALKEY_EL_TIMER(ac, tvp) \ + if ((ac)->ev.scheduleTimer && VALKEY_TIMER_ISSET(tvp)) { \ + (ac)->ev.scheduleTimer((ac)->ev.data, *(tvp)); \ + } if (ctx->c.flags & VALKEY_CONNECTED) { VALKEY_EL_TIMER(ctx, ctx->c.command_timeout); @@ -72,4 +80,4 @@ static inline void refreshTimeout(valkeyAsyncContext *ctx) { void valkeyAsyncDisconnectInternal(valkeyAsyncContext *ac); void valkeyProcessCallbacks(valkeyAsyncContext *ac); -#endif /* VALKEY_ASYNC_PRIVATE_H */ +#endif /* VALKEY_ASYNC_PRIVATE_H */ diff --git a/src/command.c b/src/command.c index a9d23c90..ba23fcde 100644 --- a/src/command.c +++ b/src/command.c @@ -41,14 +41,15 @@ #else #include #endif -#include -#include +#include "win32.h" #include "alloc.h" #include "command.h" #include "sds.h" #include "vkutil.h" -#include "win32.h" + +#include +#include #define LF (uint8_t)10 #define CR (uint8_t)13 @@ -71,12 +72,12 @@ typedef struct { /* Populate the table with code in cmddef.h generated from JSON files. */ static cmddef server_commands[] = { -#define COMMAND(_type, _name, _subname, _arity, _keymethod, _keypos) \ - {.type = CMD_REQ_VALKEY_##_type, \ - .name = _name, \ - .subname = _subname, \ - .firstkeymethod = KEYPOS_##_keymethod, \ - .firstkeypos = _keypos, \ +#define COMMAND(_type, _name, _subname, _arity, _keymethod, _keypos) \ + {.type = CMD_REQ_VALKEY_##_type, \ + .name = _name, \ + .subname = _subname, \ + .firstkeymethod = KEYPOS_##_keymethod, \ + .firstkeypos = _keypos, \ .arity = _arity}, #include "cmddef.h" #undef COMMAND diff --git a/src/command.h b/src/command.h index 911ebf13..7194142f 100644 --- a/src/command.h +++ b/src/command.h @@ -45,7 +45,7 @@ typedef enum cmd_parse_result { typedef enum cmd_type { CMD_UNKNOWN, /* Request commands */ -#define COMMAND(_type, _name, _subname, _arity, _keymethod, _keypos) \ +#define COMMAND(_type, _name, _subname, _arity, _keymethod, _keypos) \ CMD_REQ_VALKEY_##_type, #include "cmddef.h" #undef COMMAND diff --git a/src/dict.c b/src/dict.c index 9a365a80..8c13af87 100644 --- a/src/dict.c +++ b/src/dict.c @@ -34,11 +34,14 @@ */ #include "fmacros.h" + +#include "dict.h" + #include "alloc.h" -#include + #include #include -#include "dict.h" +#include /* -------------------------- private prototypes ---------------------------- */ @@ -76,7 +79,7 @@ dict *dictCreate(dictType *type, void *privDataPtr) { if (ht == NULL) return NULL; - _dictInit(ht,type,privDataPtr); + _dictInit(ht, type, privDataPtr); return ht; } @@ -100,8 +103,8 @@ int dictExpand(dict *ht, unsigned long size) { _dictInit(&n, ht->type, ht->privdata); n.size = realsize; - n.sizemask = realsize-1; - n.table = vk_calloc(realsize,sizeof(dictEntry*)); + n.sizemask = realsize - 1; + n.table = vk_calloc(realsize, sizeof(dictEntry *)); if (n.table == NULL) return DICT_ERR; @@ -112,11 +115,12 @@ int dictExpand(dict *ht, unsigned long size) { for (i = 0; i < ht->size && ht->used > 0; i++) { dictEntry *he, *nextHe; - if (ht->table[i] == NULL) continue; + if (ht->table[i] == NULL) + continue; /* For each hash entry on this slot... */ he = ht->table[i]; - while(he) { + while (he) { unsigned int h; nextHe = he->next; @@ -201,16 +205,16 @@ int dictDelete(dict *ht, const void *key) { de = ht->table[h]; prevde = NULL; - while(de) { - if (dictCompareHashKeys(ht,key,de->key)) { + while (de) { + if (dictCompareHashKeys(ht, key, de->key)) { /* Unlink the element from the list */ if (prevde) prevde->next = de->next; else ht->table[h] = de->next; - dictFreeEntryKey(ht,de); - dictFreeEntryVal(ht,de); + dictFreeEntryKey(ht, de); + dictFreeEntryVal(ht, de); vk_free(de); ht->used--; return DICT_OK; @@ -229,8 +233,9 @@ static int _dictClear(dict *ht) { for (i = 0; i < ht->size && ht->used > 0; i++) { dictEntry *he, *nextHe; - if ((he = ht->table[i]) == NULL) continue; - while(he) { + if ((he = ht->table[i]) == NULL) + continue; + while (he) { nextHe = he->next; dictFreeEntryKey(ht, he); dictFreeEntryVal(ht, he); @@ -256,10 +261,11 @@ dictEntry *dictFind(dict *ht, const void *key) { dictEntry *he; unsigned int h; - if (ht->size == 0) return NULL; + if (ht->size == 0) + return NULL; h = dictHashKey(ht, key) & ht->sizemask; he = ht->table[h]; - while(he) { + while (he) { if (dictCompareHashKeys(ht, key, he->key)) return he; he = he->next; @@ -279,7 +285,8 @@ dictEntry *dictNext(dictIterator *iter) { if (iter->entry == NULL) { iter->index++; if (iter->index >= - (signed)iter->ht->size) break; + (signed)iter->ht->size) + break; iter->entry = iter->ht->table[iter->index]; } else { iter->entry = iter->nextEntry; @@ -303,7 +310,7 @@ static int _dictExpandIfNeeded(dict *ht) { if (ht->size == 0) return dictExpand(ht, DICT_HT_INITIAL_SIZE); if (ht->used == ht->size) - return dictExpand(ht, ht->size*2); + return dictExpand(ht, ht->size * 2); return DICT_OK; } @@ -311,8 +318,9 @@ static int _dictExpandIfNeeded(dict *ht) { static unsigned long _dictNextPower(unsigned long size) { unsigned long i = DICT_HT_INITIAL_SIZE; - if (size >= LONG_MAX) return LONG_MAX; - while(1) { + if (size >= LONG_MAX) + return LONG_MAX; + while (1) { if (i >= size) return i; i *= 2; @@ -333,11 +341,10 @@ static int _dictKeyIndex(dict *ht, const void *key) { h = dictHashKey(ht, key) & ht->sizemask; /* Search if this slot does not already contain the given key */ he = ht->table[h]; - while(he) { + while (he) { if (dictCompareHashKeys(ht, key, he->key)) return -1; he = he->next; } return h; } - diff --git a/src/net.c b/src/net.c index 9c0f9038..0b4f7ce5 100644 --- a/src/net.c +++ b/src/net.c @@ -33,23 +33,25 @@ */ #include "fmacros.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "win32.h" -#include "async.h" #include "net.h" + +#include "async.h" #include "sds.h" #include "sockcompat.h" -#include "win32.h" #include "valkey_private.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + void valkeyNetClose(valkeyContext *c) { if (c && c->fd != VALKEY_INVALID_FD) { close(c->fd); @@ -63,7 +65,7 @@ static ssize_t valkeyNetRead(valkeyContext *c, char *buf, size_t bufcap) { if ((errno == EWOULDBLOCK && !(c->flags & VALKEY_BLOCK)) || (errno == EINTR)) { /* Try again later */ return 0; - } else if(errno == ETIMEDOUT && (c->flags & VALKEY_BLOCK)) { + } else if (errno == ETIMEDOUT && (c->flags & VALKEY_BLOCK)) { /* especially in windows */ valkeySetError(c, VALKEY_ERR_TIMEOUT, "recv timeout"); return -1; @@ -97,20 +99,20 @@ static ssize_t valkeyNetWrite(valkeyContext *c) { } static void valkeySetErrorFromErrno(valkeyContext *c, int type, const char *prefix) { - int errorno = errno; /* snprintf() may change errno */ - char buf[128] = { 0 }; + int errorno = errno; /* snprintf() may change errno */ + char buf[128] = {0}; size_t len = 0; if (prefix != NULL) - len = snprintf(buf,sizeof(buf),"%s: ",prefix); + len = snprintf(buf, sizeof(buf), "%s: ", prefix); strerror_r(errorno, (char *)(buf + len), sizeof(buf) - len); - valkeySetError(c,type,buf); + valkeySetError(c, type, buf); } static int valkeySetReuseAddr(valkeyContext *c) { int on = 1; if (setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,NULL); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, NULL); valkeyNetClose(c); return VALKEY_ERR; } @@ -120,7 +122,7 @@ static int valkeySetReuseAddr(valkeyContext *c) { static int valkeyCreateSocket(valkeyContext *c, int type) { valkeyFD s; if ((s = socket(type, SOCK_STREAM, 0)) == VALKEY_INVALID_FD) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,NULL); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, NULL); return VALKEY_ERR; } c->fd = s; @@ -140,7 +142,7 @@ static int valkeySetBlocking(valkeyContext *c, int blocking) { * Note that fcntl(2) for F_GETFL and F_SETFL can't be * interrupted by a signal. */ if ((flags = fcntl(c->fd, F_GETFL)) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"fcntl(F_GETFL)"); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "fcntl(F_GETFL)"); valkeyNetClose(c); return VALKEY_ERR; } @@ -151,7 +153,7 @@ static int valkeySetBlocking(valkeyContext *c, int blocking) { flags |= O_NONBLOCK; if (fcntl(c->fd, F_SETFL, flags) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"fcntl(F_SETFL)"); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "fcntl(F_SETFL)"); valkeyNetClose(c); return VALKEY_ERR; } @@ -175,8 +177,8 @@ int valkeyKeepAlive(valkeyContext *c, int interval) { return VALKEY_ERR; #ifndef _WIN32 - if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1){ - valkeySetError(c,VALKEY_ERR_OTHER,strerror(errno)); + if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1) { + valkeySetError(c, VALKEY_ERR_OTHER, strerror(errno)); return VALKEY_ERR; } @@ -184,26 +186,27 @@ int valkeyKeepAlive(valkeyContext *c, int interval) { #if defined(__APPLE__) && defined(__MACH__) if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0) { - valkeySetError(c,VALKEY_ERR_OTHER,strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, strerror(errno)); return VALKEY_ERR; } #else #if defined(__GLIBC__) && !defined(__FreeBSD_kernel__) if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) { - valkeySetError(c,VALKEY_ERR_OTHER,strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, strerror(errno)); return VALKEY_ERR; } - val = interval/3; - if (val == 0) val = 1; + val = interval / 3; + if (val == 0) + val = 1; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) { - valkeySetError(c,VALKEY_ERR_OTHER,strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, strerror(errno)); return VALKEY_ERR; } val = 3; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) { - valkeySetError(c,VALKEY_ERR_OTHER,strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, strerror(errno)); return VALKEY_ERR; } #endif @@ -223,7 +226,7 @@ int valkeyKeepAlive(valkeyContext *c, int interval) { int valkeySetTcpNoDelay(valkeyContext *c) { int yes = 1; if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"setsockopt(TCP_NODELAY)"); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "setsockopt(TCP_NODELAY)"); valkeyNetClose(c); return VALKEY_ERR; } @@ -240,7 +243,7 @@ int valkeyContextSetTcpUserTimeout(valkeyContext *c, unsigned int timeout) { (void)timeout; #endif if (res == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"setsockopt(TCP_USER_TIMEOUT)"); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "setsockopt(TCP_USER_TIMEOUT)"); valkeyNetClose(c); return VALKEY_ERR; } @@ -265,7 +268,7 @@ static int valkeyContextWaitReady(valkeyContext *c, long msec) { int res; if (errno != EINPROGRESS) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,NULL); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, NULL); valkeyNetClose(c); return VALKEY_ERR; } @@ -338,7 +341,7 @@ int valkeyCheckSocketError(valkeyContext *c) { socklen_t errlen = sizeof(err); if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"getsockopt(SO_ERROR)"); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "getsockopt(SO_ERROR)"); return VALKEY_ERR; } @@ -348,7 +351,7 @@ int valkeyCheckSocketError(valkeyContext *c) { if (err) { errno = err; - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,NULL); + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, NULL); return VALKEY_ERR; } @@ -359,12 +362,12 @@ int valkeyTcpSetTimeout(valkeyContext *c, const struct timeval tv) { const void *to_ptr = &tv; size_t to_sz = sizeof(tv); - if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,to_ptr,to_sz) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"setsockopt(SO_RCVTIMEO)"); + if (setsockopt(c->fd, SOL_SOCKET, SO_RCVTIMEO, to_ptr, to_sz) == -1) { + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "setsockopt(SO_RCVTIMEO)"); return VALKEY_ERR; } - if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,to_ptr,to_sz) == -1) { - valkeySetErrorFromErrno(c,VALKEY_ERR_IO,"setsockopt(SO_SNDTIMEO)"); + if (setsockopt(c->fd, SOL_SOCKET, SO_SNDTIMEO, to_ptr, to_sz) == -1) { + valkeySetErrorFromErrno(c, VALKEY_ERR_IO, "setsockopt(SO_SNDTIMEO)"); return VALKEY_ERR; } return VALKEY_OK; @@ -377,7 +380,7 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { int port = options->endpoint.tcp.port; valkeyFD s; int rv, n; - char _port[6]; /* strlen("65535"); */ + char _port[6]; /* strlen("65535"); */ struct addrinfo hints, *servinfo, *bservinfo, *p, *b; int blocking = (c->flags & VALKEY_BLOCK); int reuseaddr = (c->flags & VALKEY_REUSEADDR); @@ -424,7 +427,7 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { } snprintf(_port, 6, "%d", port); - memset(&hints,0,sizeof(hints)); + memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; @@ -449,26 +452,26 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { return VALKEY_ERR; } for (p = servinfo; p != NULL; p = p->ai_next) { -addrretry: - if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == VALKEY_INVALID_FD) + addrretry: + if ((s = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == VALKEY_INVALID_FD) continue; c->fd = s; - if (valkeySetBlocking(c,0) != VALKEY_OK) + if (valkeySetBlocking(c, 0) != VALKEY_OK) goto error; if (c->tcp.source_addr) { int bound = 0; /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */ if ((rv = getaddrinfo(c->tcp.source_addr, NULL, &hints, &bservinfo)) != 0) { char buf[128]; - snprintf(buf,sizeof(buf),"Can't get addr: %s",gai_strerror(rv)); - valkeySetError(c,VALKEY_ERR_OTHER,buf); + snprintf(buf, sizeof(buf), "Can't get addr: %s", gai_strerror(rv)); + valkeySetError(c, VALKEY_ERR_OTHER, buf); goto error; } if (reuseaddr) { n = 1; - if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*) &n, + if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n)) < 0) { freeaddrinfo(bservinfo); goto error; @@ -476,7 +479,7 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { } for (b = bservinfo; b != NULL; b = b->ai_next) { - if (bind(s,b->ai_addr,b->ai_addrlen) != -1) { + if (bind(s, b->ai_addr, b->ai_addrlen) != -1) { bound = 1; break; } @@ -484,8 +487,8 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { freeaddrinfo(bservinfo); if (!bound) { char buf[128]; - snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno)); - valkeySetError(c,VALKEY_ERR_OTHER,buf); + snprintf(buf, sizeof(buf), "Can't bind socket: %s", strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, buf); goto error; } } @@ -499,7 +502,7 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { memcpy(c->saddr, p->ai_addr, p->ai_addrlen); c->addrlen = p->ai_addrlen; - if (connect(s,p->ai_addr,p->ai_addrlen) == -1) { + if (connect(s, p->ai_addr, p->ai_addrlen) == -1) { if (errno == EHOSTUNREACH) { valkeyNetClose(c); continue; @@ -519,14 +522,14 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { goto addrretry; } } else { - wait_for_ready: - if (valkeyContextWaitReady(c,timeout_msec) != VALKEY_OK) + wait_for_ready: + if (valkeyContextWaitReady(c, timeout_msec) != VALKEY_OK) goto error; if (valkeySetTcpNoDelay(c) != VALKEY_OK) goto error; } } - if (blocking && valkeySetBlocking(c,1) != VALKEY_OK) + if (blocking && valkeySetBlocking(c, 1) != VALKEY_OK) goto error; c->flags |= VALKEY_CONNECTED; @@ -535,8 +538,8 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { } if (p == NULL) { char buf[128]; - snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno)); - valkeySetError(c,VALKEY_ERR_OTHER,buf); + snprintf(buf, sizeof(buf), "Can't create socket: %s", strerror(errno)); + valkeySetError(c, VALKEY_ERR_OTHER, buf); goto error; } @@ -545,11 +548,11 @@ int valkeyContextConnectTcp(valkeyContext *c, const valkeyOptions *options) { error: rv = VALKEY_ERR; end: - if(servinfo) { + if (servinfo) { freeaddrinfo(servinfo); } - return rv; // Need to return VALKEY_OK if alright + return rv; // Need to return VALKEY_OK if alright } static int valkeyContextConnectUnix(valkeyContext *c, const valkeyOptions *options) { @@ -560,9 +563,9 @@ static int valkeyContextConnectUnix(valkeyContext *c, const valkeyOptions *optio struct sockaddr_un *sa; long timeout_msec = -1; - if (valkeyCreateSocket(c,AF_UNIX) < 0) + if (valkeyCreateSocket(c, AF_UNIX) < 0) return VALKEY_ERR; - if (valkeySetBlocking(c,0) != VALKEY_OK) + if (valkeySetBlocking(c, 0) != VALKEY_OK) return VALKEY_ERR; c->connection_type = VALKEY_CONN_UNIX; @@ -582,30 +585,31 @@ static int valkeyContextConnectUnix(valkeyContext *c, const valkeyOptions *optio c->connect_timeout = NULL; } - if (valkeyConnectTimeoutMsec(c,&timeout_msec) != VALKEY_OK) + if (valkeyConnectTimeoutMsec(c, &timeout_msec) != VALKEY_OK) return VALKEY_ERR; /* Don't leak sockaddr if we're reconnecting */ - if (c->saddr) vk_free(c->saddr); + if (c->saddr) + vk_free(c->saddr); - sa = (struct sockaddr_un*)(c->saddr = vk_malloc(sizeof(struct sockaddr_un))); + sa = (struct sockaddr_un *)(c->saddr = vk_malloc(sizeof(struct sockaddr_un))); if (sa == NULL) goto oom; c->addrlen = sizeof(struct sockaddr_un); sa->sun_family = AF_UNIX; strncpy(sa->sun_path, path, sizeof(sa->sun_path) - 1); - if (connect(c->fd, (struct sockaddr*)sa, sizeof(*sa)) == -1) { + if (connect(c->fd, (struct sockaddr *)sa, sizeof(*sa)) == -1) { if (errno == EINPROGRESS && !blocking) { /* This is ok. */ } else { - if (valkeyContextWaitReady(c,timeout_msec) != VALKEY_OK) + if (valkeyContextWaitReady(c, timeout_msec) != VALKEY_OK) return VALKEY_ERR; } } /* Reset socket to be blocking after connect(2). */ - if (blocking && valkeySetBlocking(c,1) != VALKEY_OK) + if (blocking && valkeySetBlocking(c, 1) != VALKEY_OK) return VALKEY_ERR; c->flags |= VALKEY_CONNECTED; @@ -629,7 +633,7 @@ static valkeyContextFuncs valkeyContextTcpFuncs = { .async_write = valkeyAsyncWrite, .read = valkeyNetRead, .write = valkeyNetWrite, - .set_timeout = valkeyTcpSetTimeout + .set_timeout = valkeyTcpSetTimeout, }; void valkeyContextRegisterTcpFuncs(void) { @@ -644,7 +648,7 @@ static valkeyContextFuncs valkeyContextUnixFuncs = { .async_write = valkeyAsyncWrite, .read = valkeyNetRead, .write = valkeyNetWrite, - .set_timeout = valkeyTcpSetTimeout + .set_timeout = valkeyTcpSetTimeout, }; void valkeyContextRegisterUnixFuncs(void) { @@ -666,7 +670,7 @@ static valkeyContextFuncs valkeyContextUserfdFuncs = { .async_write = valkeyAsyncWrite, .read = valkeyNetRead, .write = valkeyNetWrite, - .set_timeout = valkeyTcpSetTimeout + .set_timeout = valkeyTcpSetTimeout, }; void valkeyContextRegisterUserfdFuncs(void) { diff --git a/src/rdma.c b/src/rdma.c index 9d3f5891..fd4cddb2 100644 --- a/src/rdma.c +++ b/src/rdma.c @@ -28,14 +28,14 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#ifdef __linux__ /* currently RDMA is only supported on Linux */ +#ifdef __linux__ /* currently RDMA is only supported on Linux */ #define _GNU_SOURCE -#include "valkey.h" #include "async.h" -#include "vkutil.h" -#include "valkey_rdma.h" +#include "valkey.h" #include "valkey_private.h" +#include "valkey_rdma.h" +#include "vkutil.h" #include #include @@ -95,7 +95,7 @@ typedef enum valkeyRdmaOpcode { } valkeyRdmaOpcode; #define VALKEY_RDMA_MAX_WQE 1024 -#define VALKEY_RDMA_DEFAULT_RX_LEN (1024*1024) +#define VALKEY_RDMA_DEFAULT_RX_LEN (1024 * 1024) #define VALKEY_RDMA_INVALID_OPCODE 0xffff typedef struct RdmaContext { @@ -156,7 +156,6 @@ static int rdmaPostRecv(RdmaContext *ctx, struct rdma_cm_id *cm_id, valkeyRdmaCm size_t length = sizeof(valkeyRdmaCmd); struct ibv_recv_wr recv_wr, *bad_wr; - sge.addr = (uint64_t)(uintptr_t)cmd; sge.length = length; sge.lkey = ctx->cmd_mr->lkey; @@ -173,8 +172,7 @@ static int rdmaPostRecv(RdmaContext *ctx, struct rdma_cm_id *cm_id, valkeyRdmaCm return VALKEY_OK; } -static void rdmaDestroyIoBuf(RdmaContext *ctx) -{ +static void rdmaDestroyIoBuf(RdmaContext *ctx) { if (ctx->recv_mr) { ibv_dereg_mr(ctx->recv_mr); ctx->recv_mr = NULL; @@ -275,7 +273,6 @@ static int rdmaAdjustSendbuf(valkeyContext *c, RdmaContext *ctx, unsigned int le return VALKEY_OK; } - static int rdmaSendCommand(valkeyContext *c, struct rdma_cm_id *cm_id, valkeyRdmaCmd *cmd) { RdmaContext *ctx = c->privctx; struct ibv_send_wr send_wr, *bad_wr; @@ -319,7 +316,7 @@ static int rdmaSendCommand(valkeyContext *c, struct rdma_cm_id *cm_id, valkeyRdm static int connRdmaRegisterRx(valkeyContext *c, struct rdma_cm_id *cm_id) { RdmaContext *ctx = c->privctx; - valkeyRdmaCmd cmd = { 0 }; + valkeyRdmaCmd cmd = {0}; cmd.memory.opcode = htons(RegisterXferMemory); cmd.memory.addr = htobe64((uint64_t)ctx->recv_buf); @@ -458,8 +455,8 @@ static int connRdmaHandleCq(valkeyContext *c) { * Return OK on CQ event ready, then CQ event should be handled outside. */ static int valkeyRdmaPollCqCm(valkeyContext *c, long timed) { -#define VALKEY_RDMA_POLLFD_CM 0 -#define VALKEY_RDMA_POLLFD_CQ 1 +#define VALKEY_RDMA_POLLFD_CM 0 +#define VALKEY_RDMA_POLLFD_CQ 1 #define VALKEY_RDMA_POLLFD_MAX 2 struct pollfd pfd[VALKEY_RDMA_POLLFD_MAX]; RdmaContext *ctx = c->privctx; @@ -539,7 +536,6 @@ static ssize_t valkeyRdmaRead(valkeyContext *c, char *buf, size_t bufcap) { } } - static size_t connRdmaSend(RdmaContext *ctx, struct rdma_cm_id *cm_id, const void *data, size_t data_len) { struct ibv_send_wr send_wr, *bad_wr; struct ibv_sge sge; @@ -802,7 +798,7 @@ static int valkeyRdmaWaitConn(valkeyContext *c, long timeout) { long now, end; RdmaContext *ctx = c->privctx; - assert (timeout >= 0); + assert(timeout >= 0); end = vk_msec_now() + timeout; while (1) { @@ -835,7 +831,7 @@ static int valkeyContextConnectRdma(valkeyContext *c, const valkeyOptions *optio const char *addr = options->endpoint.tcp.ip; int port = options->endpoint.tcp.port; int ret; - char _port[6]; /* strlen("65535"); */ + char _port[6]; /* strlen("65535"); */ struct addrinfo hints, *servinfo, *p; long timeout_msec = -1; struct rdma_event_channel *cm_channel = NULL; @@ -885,8 +881,8 @@ static int valkeyContextConnectRdma(valkeyContext *c, const valkeyOptions *optio hints.ai_socktype = SOCK_STREAM; if ((ret = getaddrinfo(c->tcp.host, _port, &hints, &servinfo)) != 0) { - hints.ai_family = AF_INET6; - if ((ret = getaddrinfo(addr, _port, &hints, &servinfo)) != 0) { + hints.ai_family = AF_INET6; + if ((ret = getaddrinfo(addr, _port, &hints, &servinfo)) != 0) { valkeySetError(c, VALKEY_ERR_OTHER, gai_strerror(ret)); return VALKEY_ERR; } @@ -921,11 +917,11 @@ static int valkeyContextConnectRdma(valkeyContext *c, const valkeyOptions *optio for (p = servinfo; p != NULL; p = p->ai_next) { if (p->ai_family == PF_INET) { - memcpy(&saddr, p->ai_addr, sizeof(struct sockaddr_in)); - ((struct sockaddr_in *)&saddr)->sin_port = htons(port); + memcpy(&saddr, p->ai_addr, sizeof(struct sockaddr_in)); + ((struct sockaddr_in *)&saddr)->sin_port = htons(port); } else if (p->ai_family == PF_INET6) { - memcpy(&saddr, p->ai_addr, sizeof(struct sockaddr_in6)); - ((struct sockaddr_in6 *)&saddr)->sin6_port = htons(port); + memcpy(&saddr, p->ai_addr, sizeof(struct sockaddr_in6)); + ((struct sockaddr_in6 *)&saddr)->sin6_port = htons(port); } else { valkeySetError(c, VALKEY_ERR_PROTOCOL, "RDMA: unsupported family"); goto free_rdma; @@ -962,7 +958,7 @@ static int valkeyContextConnectRdma(valkeyContext *c, const valkeyOptions *optio } end: - if(servinfo) { + if (servinfo) { freeaddrinfo(servinfo); } @@ -982,8 +978,7 @@ static valkeyContextFuncs valkeyContextRdmaFuncs = { .async_write = valkeyRdmaAsyncWrite, .read = valkeyRdmaRead, .write = valkeyRdmaWrite, - .set_timeout = valkeyRdmaSetTimeout -}; + .set_timeout = valkeyRdmaSetTimeout}; int valkeyInitiateRdma(void) { valkeyContextRegisterFuncs(&valkeyContextRdmaFuncs, VALKEY_CONN_RDMA); @@ -991,8 +986,8 @@ int valkeyInitiateRdma(void) { return VALKEY_OK; } -#else /* __linux__ */ +#else /* __linux__ */ #error "BUILD ERROR: RDMA is only supported on linux" -#endif /* __linux__ */ +#endif /* __linux__ */ diff --git a/src/read.c b/src/read.c index 07f97ed1..617ddd0a 100644 --- a/src/read.c +++ b/src/read.c @@ -30,22 +30,24 @@ */ #include "fmacros.h" -#include + #include +#include #ifndef _MSC_VER -#include #include +#include #endif -#include -#include -#include -#include -#include +#include "win32.h" #include "alloc.h" #include "read.h" #include "sds.h" -#include "win32.h" + +#include +#include +#include +#include +#include /* Initial size of our nested reply stack and how much we grow it when needd */ #define VALKEY_READER_STACK_SIZE 9 @@ -69,29 +71,39 @@ static void valkeyReaderSetError(valkeyReader *r, int type, const char *str) { /* Set error. */ r->err = type; len = strlen(str); - len = len < (sizeof(r->errstr)-1) ? len : (sizeof(r->errstr)-1); - memcpy(r->errstr,str,len); + len = len < (sizeof(r->errstr) - 1) ? len : (sizeof(r->errstr) - 1); + memcpy(r->errstr, str, len); r->errstr[len] = '\0'; } static size_t chrtos(char *buf, size_t size, char byte) { size_t len = 0; - switch(byte) { + switch (byte) { case '\\': case '"': - len = snprintf(buf,size,"\"\\%c\"",byte); + len = snprintf(buf, size, "\"\\%c\"", byte); + break; + case '\n': + len = snprintf(buf, size, "\"\\n\""); + break; + case '\r': + len = snprintf(buf, size, "\"\\r\""); + break; + case '\t': + len = snprintf(buf, size, "\"\\t\""); + break; + case '\a': + len = snprintf(buf, size, "\"\\a\""); + break; + case '\b': + len = snprintf(buf, size, "\"\\b\""); break; - case '\n': len = snprintf(buf,size,"\"\\n\""); break; - case '\r': len = snprintf(buf,size,"\"\\r\""); break; - case '\t': len = snprintf(buf,size,"\"\\t\""); break; - case '\a': len = snprintf(buf,size,"\"\\a\""); break; - case '\b': len = snprintf(buf,size,"\"\\b\""); break; default: if (isprint(byte)) - len = snprintf(buf,size,"\"%c\"",byte); + len = snprintf(buf, size, "\"%c\"", byte); else - len = snprintf(buf,size,"\"\\x%02x\"",(unsigned char)byte); + len = snprintf(buf, size, "\"\\x%02x\"", (unsigned char)byte); break; } @@ -101,20 +113,20 @@ static size_t chrtos(char *buf, size_t size, char byte) { static void valkeyReaderSetErrorProtocolByte(valkeyReader *r, char byte) { char cbuf[8], sbuf[128]; - chrtos(cbuf,sizeof(cbuf),byte); - snprintf(sbuf,sizeof(sbuf), - "Protocol error, got %s as reply type byte", cbuf); - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL,sbuf); + chrtos(cbuf, sizeof(cbuf), byte); + snprintf(sbuf, sizeof(sbuf), + "Protocol error, got %s as reply type byte", cbuf); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, sbuf); } static void valkeyReaderSetErrorOOM(valkeyReader *r) { - valkeyReaderSetError(r,VALKEY_ERR_OOM,"Out of memory"); + valkeyReaderSetError(r, VALKEY_ERR_OOM, "Out of memory"); } static char *readBytes(valkeyReader *r, unsigned int bytes) { char *p; - if (r->len-r->pos >= bytes) { - p = r->buf+r->pos; + if (r->len - r->pos >= bytes) { + p = r->buf + r->pos; r->pos += bytes; return p; } @@ -170,13 +182,15 @@ static int string2ll(const char *s, size_t slen, long long *value) { /* Special case: first and only digit is 0. */ if (slen == 1 && p[0] == '0') { - if (value != NULL) *value = 0; + if (value != NULL) + *value = 0; return VALKEY_OK; } if (p[0] == '-') { negative = 1; - p++; plen++; + p++; + plen++; /* Abort on only a negative sign. */ if (plen == slen) @@ -185,8 +199,9 @@ static int string2ll(const char *s, size_t slen, long long *value) { /* First digit should be 1-9, otherwise the string should just be 0. */ if (p[0] >= '1' && p[0] <= '9') { - v = p[0]-'0'; - p++; plen++; + v = p[0] - '0'; + p++; + plen++; } else if (p[0] == '0' && slen == 1) { *value = 0; return VALKEY_OK; @@ -199,11 +214,12 @@ static int string2ll(const char *s, size_t slen, long long *value) { return VALKEY_ERR; v *= 10; - if (v > (ULLONG_MAX - (p[0]-'0'))) /* Overflow. */ + if (v > (ULLONG_MAX - (p[0] - '0'))) /* Overflow. */ return VALKEY_ERR; - v += p[0]-'0'; + v += p[0] - '0'; - p++; plen++; + p++; + plen++; } /* Return if not all bytes were used. */ @@ -211,13 +227,15 @@ static int string2ll(const char *s, size_t slen, long long *value) { return VALKEY_ERR; if (negative) { - if (v > ((unsigned long long)(-(LLONG_MIN+1))+1)) /* Overflow. */ + if (v > ((unsigned long long)(-(LLONG_MIN + 1)) + 1)) /* Overflow. */ return VALKEY_ERR; - if (value != NULL) *value = -v; + if (value != NULL) + *value = -v; } else { if (v > LLONG_MAX) /* Overflow. */ return VALKEY_ERR; - if (value != NULL) *value = v; + if (value != NULL) + *value = v; } return VALKEY_OK; } @@ -226,12 +244,13 @@ static char *readLine(valkeyReader *r, int *_len) { char *p, *s; int len; - p = r->buf+r->pos; - s = seekNewline(p,(r->len-r->pos)); + p = r->buf + r->pos; + s = seekNewline(p, (r->len - r->pos)); if (s != NULL) { - len = s-(r->buf+r->pos); - r->pos += len+2; /* skip \r\n */ - if (_len) *_len = len; + len = s - (r->buf + r->pos); + r->pos += len + 2; /* skip \r\n */ + if (_len) + *_len = len; return p; } return NULL; @@ -247,13 +266,13 @@ static void moveToNextTask(valkeyReader *r) { } cur = r->task[r->ridx]; - prv = r->task[r->ridx-1]; + prv = r->task[r->ridx - 1]; assert(prv->type == VALKEY_REPLY_ARRAY || prv->type == VALKEY_REPLY_MAP || prv->type == VALKEY_REPLY_ATTR || prv->type == VALKEY_REPLY_SET || prv->type == VALKEY_REPLY_PUSH); - if (cur->idx == prv->elements-1) { + if (cur->idx == prv->elements - 1) { r->ridx--; } else { /* Reset the type because the next item can be anything */ @@ -272,113 +291,114 @@ static int processLineItem(valkeyReader *r) { char *p; int len; - if ((p = readLine(r,&len)) != NULL) { + if ((p = readLine(r, &len)) != NULL) { if (cur->type == VALKEY_REPLY_INTEGER) { long long v; if (string2ll(p, len, &v) == VALKEY_ERR) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad integer value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad integer value"); return VALKEY_ERR; } if (r->fn && r->fn->createInteger) { - obj = r->fn->createInteger(cur,v); + obj = r->fn->createInteger(cur, v); } else { - obj = (void*)VALKEY_REPLY_INTEGER; + obj = (void *)VALKEY_REPLY_INTEGER; } } else if (cur->type == VALKEY_REPLY_DOUBLE) { char buf[326], *eptr; double d; if ((size_t)len >= sizeof(buf)) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Double value is too large"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Double value is too large"); return VALKEY_ERR; } - memcpy(buf,p,len); + memcpy(buf, p, len); buf[len] = '\0'; - if (len == 3 && strcasecmp(buf,"inf") == 0) { + if (len == 3 && strcasecmp(buf, "inf") == 0) { d = INFINITY; /* Positive infinite. */ - } else if (len == 4 && strcasecmp(buf,"-inf") == 0) { + } else if (len == 4 && strcasecmp(buf, "-inf") == 0) { d = -INFINITY; /* Negative infinite. */ - } else if ((len == 3 && strcasecmp(buf,"nan") == 0) || + } else if ((len == 3 && strcasecmp(buf, "nan") == 0) || (len == 4 && strcasecmp(buf, "-nan") == 0)) { d = NAN; /* nan. */ } else { - d = strtod((char*)buf,&eptr); + d = strtod((char *)buf, &eptr); /* RESP3 only allows "inf", "-inf", and finite values, while * strtod() allows other variations on infinity, * etc. We explicity handle our two allowed infinite cases and NaN * above, so strtod() should only result in finite values. */ if (buf[0] == '\0' || eptr != &buf[len] || !isfinite(d)) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad double value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad double value"); return VALKEY_ERR; } } if (r->fn && r->fn->createDouble) { - obj = r->fn->createDouble(cur,d,buf,len); + obj = r->fn->createDouble(cur, d, buf, len); } else { - obj = (void*)VALKEY_REPLY_DOUBLE; + obj = (void *)VALKEY_REPLY_DOUBLE; } } else if (cur->type == VALKEY_REPLY_NIL) { if (len != 0) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad nil value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad nil value"); return VALKEY_ERR; } if (r->fn && r->fn->createNil) obj = r->fn->createNil(cur); else - obj = (void*)VALKEY_REPLY_NIL; + obj = (void *)VALKEY_REPLY_NIL; } else if (cur->type == VALKEY_REPLY_BOOL) { int bval; if (len != 1 || !strchr("tTfF", p[0])) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad bool value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad bool value"); return VALKEY_ERR; } bval = p[0] == 't' || p[0] == 'T'; if (r->fn && r->fn->createBool) - obj = r->fn->createBool(cur,bval); + obj = r->fn->createBool(cur, bval); else - obj = (void*)VALKEY_REPLY_BOOL; + obj = (void *)VALKEY_REPLY_BOOL; } else if (cur->type == VALKEY_REPLY_BIGNUM) { /* Ensure all characters are decimal digits (with possible leading * minus sign). */ for (int i = 0; i < len; i++) { /* XXX Consider: Allow leading '+'? Error on leading '0's? */ - if (i == 0 && p[0] == '-') continue; + if (i == 0 && p[0] == '-') + continue; if (p[i] < '0' || p[i] > '9') { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad bignum value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad bignum value"); return VALKEY_ERR; } } if (r->fn && r->fn->createString) - obj = r->fn->createString(cur,p,len); + obj = r->fn->createString(cur, p, len); else - obj = (void*)VALKEY_REPLY_BIGNUM; + obj = (void *)VALKEY_REPLY_BIGNUM; } else { /* Type will be error or status. */ for (int i = 0; i < len; i++) { if (p[i] == '\r' || p[i] == '\n') { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad simple string value"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad simple string value"); return VALKEY_ERR; } } if (r->fn && r->fn->createString) - obj = r->fn->createString(cur,p,len); + obj = r->fn->createString(cur, p, len); else - obj = (void*)(uintptr_t)(cur->type); + obj = (void *)(uintptr_t)(cur->type); } if (obj == NULL) { @@ -387,7 +407,8 @@ static int processLineItem(valkeyReader *r) { } /* Set reply if this is the root object. */ - if (r->ridx == 0) r->reply = obj; + if (r->ridx == 0) + r->reply = obj; moveToNextTask(r); return VALKEY_OK; } @@ -403,21 +424,21 @@ static int processBulkItem(valkeyReader *r) { unsigned long bytelen; int success = 0; - p = r->buf+r->pos; - s = seekNewline(p,r->len-r->pos); + p = r->buf + r->pos; + s = seekNewline(p, r->len - r->pos); if (s != NULL) { - p = r->buf+r->pos; - bytelen = s-(r->buf+r->pos)+2; /* include \r\n */ + p = r->buf + r->pos; + bytelen = s - (r->buf + r->pos) + 2; /* include \r\n */ if (string2ll(p, bytelen - 2, &len) == VALKEY_ERR) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad bulk string length"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad bulk string length"); return VALKEY_ERR; } if (len < -1 || (LLONG_MAX > SIZE_MAX && len > (long long)SIZE_MAX)) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bulk string length out of range"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bulk string length out of range"); return VALKEY_ERR; } @@ -426,24 +447,23 @@ static int processBulkItem(valkeyReader *r) { if (r->fn && r->fn->createNil) obj = r->fn->createNil(cur); else - obj = (void*)VALKEY_REPLY_NIL; + obj = (void *)VALKEY_REPLY_NIL; success = 1; } else { /* Only continue when the buffer contains the entire bulk item. */ - bytelen += len+2; /* include \r\n */ - if (r->pos+bytelen <= r->len) { + bytelen += len + 2; /* include \r\n */ + if (r->pos + bytelen <= r->len) { if ((cur->type == VALKEY_REPLY_VERB && len < 4) || - (cur->type == VALKEY_REPLY_VERB && s[5] != ':')) - { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Verbatim string 4 bytes of content type are " - "missing or incorrectly encoded."); + (cur->type == VALKEY_REPLY_VERB && s[5] != ':')) { + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Verbatim string 4 bytes of content type are " + "missing or incorrectly encoded."); return VALKEY_ERR; } if (r->fn && r->fn->createString) - obj = r->fn->createString(cur,s+2,len); + obj = r->fn->createString(cur, s + 2, len); else - obj = (void*)(uintptr_t)cur->type; + obj = (void *)(uintptr_t)cur->type; success = 1; } } @@ -458,7 +478,8 @@ static int processBulkItem(valkeyReader *r) { r->pos += bytelen; /* Set reply if this is the root object. */ - if (r->ridx == 0) r->reply = obj; + if (r->ridx == 0) + r->reply = obj; moveToNextTask(r); return VALKEY_OK; } @@ -505,20 +526,19 @@ static int processAggregateItem(valkeyReader *r) { return VALKEY_ERR; } - if ((p = readLine(r,&len)) != NULL) { + if ((p = readLine(r, &len)) != NULL) { if (string2ll(p, len, &elements) == VALKEY_ERR) { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Bad multi-bulk length"); + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Bad multi-bulk length"); return VALKEY_ERR; } root = (r->ridx == 0); if (elements < -1 || (LLONG_MAX > SIZE_MAX && elements > SIZE_MAX) || - (r->maxelements > 0 && elements > r->maxelements)) - { - valkeyReaderSetError(r,VALKEY_ERR_PROTOCOL, - "Multi-bulk length out of range"); + (r->maxelements > 0 && elements > r->maxelements)) { + valkeyReaderSetError(r, VALKEY_ERR_PROTOCOL, + "Multi-bulk length out of range"); return VALKEY_ERR; } @@ -526,7 +546,7 @@ static int processAggregateItem(valkeyReader *r) { if (r->fn && r->fn->createNil) obj = r->fn->createNil(cur); else - obj = (void*)VALKEY_REPLY_NIL; + obj = (void *)VALKEY_REPLY_NIL; if (obj == NULL) { valkeyReaderSetErrorOOM(r); @@ -535,12 +555,13 @@ static int processAggregateItem(valkeyReader *r) { moveToNextTask(r); } else { - if (cur->type == VALKEY_REPLY_MAP || cur->type == VALKEY_REPLY_ATTR) elements *= 2; + if (cur->type == VALKEY_REPLY_MAP || cur->type == VALKEY_REPLY_ATTR) + elements *= 2; if (r->fn && r->fn->createArray) - obj = r->fn->createArray(cur,elements); + obj = r->fn->createArray(cur, elements); else - obj = (void*)(uintptr_t)cur->type; + obj = (void *)(uintptr_t)cur->type; if (obj == NULL) { valkeyReaderSetErrorOOM(r); @@ -564,7 +585,8 @@ static int processAggregateItem(valkeyReader *r) { } /* Set reply if this is the root object. */ - if (root) r->reply = obj; + if (root) + r->reply = obj; return VALKEY_OK; } @@ -577,7 +599,7 @@ static int processItem(valkeyReader *r) { /* check if we need to read type */ if (cur->type < 0) { - if ((p = readBytes(r,1)) != NULL) { + if ((p = readBytes(r, 1)) != NULL) { switch (p[0]) { case '-': cur->type = VALKEY_REPLY_ERROR; @@ -622,7 +644,7 @@ static int processItem(valkeyReader *r) { cur->type = VALKEY_REPLY_BIGNUM; break; default: - valkeyReaderSetErrorProtocolByte(r,*p); + valkeyReaderSetErrorProtocolByte(r, *p); return VALKEY_ERR; } } else { @@ -632,7 +654,7 @@ static int processItem(valkeyReader *r) { } /* process typed item */ - switch(cur->type) { + switch (cur->type) { case VALKEY_REPLY_ERROR: case VALKEY_REPLY_STATUS: case VALKEY_REPLY_INTEGER: @@ -659,7 +681,7 @@ static int processItem(valkeyReader *r) { valkeyReader *valkeyReaderCreateWithFunctions(valkeyReplyObjectFunctions *fn) { valkeyReader *r; - r = vk_calloc(1,sizeof(valkeyReader)); + r = vk_calloc(1, sizeof(valkeyReader)); if (r == NULL) return NULL; @@ -721,13 +743,15 @@ int valkeyReaderFeed(valkeyReader *r, const char *buf, size_t len) { if (r->len == 0 && r->maxbuf != 0 && sdsavail(r->buf) > r->maxbuf) { sdsfree(r->buf); r->buf = sdsempty(); - if (r->buf == 0) goto oom; + if (r->buf == 0) + goto oom; r->pos = 0; } - newbuf = sdscatlen(r->buf,buf,len); - if (newbuf == NULL) goto oom; + newbuf = sdscatlen(r->buf, buf, len); + if (newbuf == NULL) + goto oom; r->buf = newbuf; r->len = sdslen(r->buf); @@ -775,7 +799,8 @@ int valkeyReaderGetReply(valkeyReader *r, void **reply) { /* Discard part of the buffer when we've consumed at least 1k, to avoid * doing unnecessary calls to memmove() in sds.c. */ if (r->pos >= 1024) { - if (sdsrange(r->buf,r->pos,-1) < 0) return VALKEY_ERR; + if (sdsrange(r->buf, r->pos, -1) < 0) + return VALKEY_ERR; r->pos = 0; r->len = sdslen(r->buf); } diff --git a/src/sds.c b/src/sds.c index c0388bdd..ab6295d3 100644 --- a/src/sds.c +++ b/src/sds.c @@ -31,27 +31,30 @@ */ #include "fmacros.h" + +#include "sds.h" + +#include "sdsalloc.h" + +#include +#include +#include #include #include #include -#include -#include -#include -#include "sds.h" -#include "sdsalloc.h" static inline int sdsHdrSize(char type) { - switch(type&SDS_TYPE_MASK) { - case SDS_TYPE_5: - return sizeof(struct sdshdr5); - case SDS_TYPE_8: - return sizeof(struct sdshdr8); - case SDS_TYPE_16: - return sizeof(struct sdshdr16); - case SDS_TYPE_32: - return sizeof(struct sdshdr32); - case SDS_TYPE_64: - return sizeof(struct sdshdr64); + switch (type & SDS_TYPE_MASK) { + case SDS_TYPE_5: + return sizeof(struct sdshdr5); + case SDS_TYPE_8: + return sizeof(struct sdshdr8); + case SDS_TYPE_16: + return sizeof(struct sdshdr16); + case SDS_TYPE_32: + return sizeof(struct sdshdr32); + case SDS_TYPE_64: + return sizeof(struct sdshdr64); } return 0; } @@ -86,50 +89,53 @@ sds sdsnewlen(const void *init, size_t initlen) { char type = sdsReqType(initlen); /* Empty strings are usually created in order to append. Use type 8 * since type 5 is not good at this. */ - if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8; + if (type == SDS_TYPE_5 && initlen == 0) + type = SDS_TYPE_8; int hdrlen = sdsHdrSize(type); unsigned char *fp; /* flags pointer. */ - if (hdrlen+initlen+1 <= initlen) return NULL; /* Catch size_t overflow */ - sh = s_malloc(hdrlen+initlen+1); - if (sh == NULL) return NULL; + if (hdrlen + initlen + 1 <= initlen) + return NULL; /* Catch size_t overflow */ + sh = s_malloc(hdrlen + initlen + 1); + if (sh == NULL) + return NULL; if (!init) - memset(sh, 0, hdrlen+initlen+1); - s = (char*)sh+hdrlen; - fp = ((unsigned char*)s)-1; - switch(type) { - case SDS_TYPE_5: { - *fp = type | (initlen << SDS_TYPE_BITS); - break; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - sh->len = initlen; - sh->alloc = initlen; - *fp = type; - break; - } + memset(sh, 0, hdrlen + initlen + 1); + s = (char *)sh + hdrlen; + fp = ((unsigned char *)s) - 1; + switch (type) { + case SDS_TYPE_5: { + *fp = type | (initlen << SDS_TYPE_BITS); + break; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8, s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16, s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32, s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64, s); + sh->len = initlen; + sh->alloc = initlen; + *fp = type; + break; + } } if (initlen && init) memcpy(s, init, initlen); @@ -140,7 +146,7 @@ sds sdsnewlen(const void *init, size_t initlen) { /* Create an empty (zero length) sds string. Even in this case the string * always has an implicit null term. */ sds sdsempty(void) { - return sdsnewlen("",0); + return sdsnewlen("", 0); } /* Create a new sds string starting from a null terminated C string. */ @@ -156,8 +162,9 @@ sds sdsdup(const sds s) { /* Free an sds string. No operation is performed if 's' is NULL. */ void sdsfree(sds s) { - if (s == NULL) return; - s_free((char*)s-sdsHdrSize(s[-1])); + if (s == NULL) + return; + s_free((char *)s - sdsHdrSize(s[-1])); } /* Set the sds string length to the length as obtained with strlen(), so @@ -202,12 +209,14 @@ sds sdsMakeRoomFor(sds s, size_t addlen) { int hdrlen; /* Return ASAP if there is enough space left. */ - if (avail >= addlen) return s; + if (avail >= addlen) + return s; len = sdslen(s); - sh = (char*)s-sdsHdrSize(oldtype); - reqlen = newlen = (len+addlen); - if (newlen <= len) return NULL; /* Catch size_t overflow */ + sh = (char *)s - sdsHdrSize(oldtype); + reqlen = newlen = (len + addlen); + if (newlen <= len) + return NULL; /* Catch size_t overflow */ if (newlen < SDS_MAX_PREALLOC) newlen *= 2; else @@ -218,22 +227,26 @@ sds sdsMakeRoomFor(sds s, size_t addlen) { /* Don't use type 5: the user is appending to the string and type 5 is * not able to remember empty space, so sdsMakeRoomFor() must be called * at every appending operation. */ - if (type == SDS_TYPE_5) type = SDS_TYPE_8; + if (type == SDS_TYPE_5) + type = SDS_TYPE_8; hdrlen = sdsHdrSize(type); - if (hdrlen+newlen+1 <= reqlen) return NULL; /* Catch size_t overflow */ - if (oldtype==type) { - newsh = s_realloc(sh, hdrlen+newlen+1); - if (newsh == NULL) return NULL; - s = (char*)newsh+hdrlen; + if (hdrlen + newlen + 1 <= reqlen) + return NULL; /* Catch size_t overflow */ + if (oldtype == type) { + newsh = s_realloc(sh, hdrlen + newlen + 1); + if (newsh == NULL) + return NULL; + s = (char *)newsh + hdrlen; } else { /* Since the header size changes, need to move the string forward, * and can't use realloc */ - newsh = s_malloc(hdrlen+newlen+1); - if (newsh == NULL) return NULL; - memcpy((char*)newsh+hdrlen, s, len+1); + newsh = s_malloc(hdrlen + newlen + 1); + if (newsh == NULL) + return NULL; + memcpy((char *)newsh + hdrlen, s, len + 1); s_free(sh); - s = (char*)newsh+hdrlen; + s = (char *)newsh + hdrlen; s[-1] = type; sdssetlen(s, len); } @@ -252,20 +265,22 @@ sds sdsRemoveFreeSpace(sds s) { char type, oldtype = s[-1] & SDS_TYPE_MASK; int hdrlen; size_t len = sdslen(s); - sh = (char*)s-sdsHdrSize(oldtype); + sh = (char *)s - sdsHdrSize(oldtype); type = sdsReqType(len); hdrlen = sdsHdrSize(type); - if (oldtype==type) { - newsh = s_realloc(sh, hdrlen+len+1); - if (newsh == NULL) return NULL; - s = (char*)newsh+hdrlen; + if (oldtype == type) { + newsh = s_realloc(sh, hdrlen + len + 1); + if (newsh == NULL) + return NULL; + s = (char *)newsh + hdrlen; } else { - newsh = s_malloc(hdrlen+len+1); - if (newsh == NULL) return NULL; - memcpy((char*)newsh+hdrlen, s, len+1); + newsh = s_malloc(hdrlen + len + 1); + if (newsh == NULL) + return NULL; + memcpy((char *)newsh + hdrlen, s, len + 1); s_free(sh); - s = (char*)newsh+hdrlen; + s = (char *)newsh + hdrlen; s[-1] = type; sdssetlen(s, len); } @@ -282,13 +297,13 @@ sds sdsRemoveFreeSpace(sds s) { */ size_t sdsAllocSize(sds s) { size_t alloc = sdsalloc(s); - return sdsHdrSize(s[-1])+alloc+1; + return sdsHdrSize(s[-1]) + alloc + 1; } /* Return the pointer of the actual SDS allocation (normally SDS strings * are referenced by the start of the string buffer). */ void *sdsAllocPtr(sds s) { - return (void*) (s-sdsHdrSize(s[-1])); + return (void *)(s - sdsHdrSize(s[-1])); } /* Increment the sds length and decrements the left free space at the @@ -317,40 +332,41 @@ void *sdsAllocPtr(sds s) { void sdsIncrLen(sds s, int incr) { unsigned char flags = s[-1]; size_t len; - switch(flags&SDS_TYPE_MASK) { - case SDS_TYPE_5: { - unsigned char *fp = ((unsigned char*)s)-1; - unsigned char oldlen = SDS_TYPE_5_LEN(flags); - assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr))); - *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS); - len = oldlen+incr; - break; - } - case SDS_TYPE_8: { - SDS_HDR_VAR(8,s); - assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_16: { - SDS_HDR_VAR(16,s); - assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_32: { - SDS_HDR_VAR(32,s); - assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); - len = (sh->len += incr); - break; - } - case SDS_TYPE_64: { - SDS_HDR_VAR(64,s); - assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr))); - len = (sh->len += incr); - break; - } - default: len = 0; /* Just to avoid compilation warnings. */ + switch (flags & SDS_TYPE_MASK) { + case SDS_TYPE_5: { + unsigned char *fp = ((unsigned char *)s) - 1; + unsigned char oldlen = SDS_TYPE_5_LEN(flags); + assert((incr > 0 && oldlen + incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr))); + *fp = SDS_TYPE_5 | ((oldlen + incr) << SDS_TYPE_BITS); + len = oldlen + incr; + break; + } + case SDS_TYPE_8: { + SDS_HDR_VAR(8, s); + assert((incr >= 0 && sh->alloc - sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_16: { + SDS_HDR_VAR(16, s); + assert((incr >= 0 && sh->alloc - sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_32: { + SDS_HDR_VAR(32, s); + assert((incr >= 0 && sh->alloc - sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); + len = (sh->len += incr); + break; + } + case SDS_TYPE_64: { + SDS_HDR_VAR(64, s); + assert((incr >= 0 && sh->alloc - sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr))); + len = (sh->len += incr); + break; + } + default: + len = 0; /* Just to avoid compilation warnings. */ } s[len] = '\0'; } @@ -363,12 +379,14 @@ void sdsIncrLen(sds s, int incr) { sds sdsgrowzero(sds s, size_t len) { size_t curlen = sdslen(s); - if (len <= curlen) return s; - s = sdsMakeRoomFor(s,len-curlen); - if (s == NULL) return NULL; + if (len <= curlen) + return s; + s = sdsMakeRoomFor(s, len - curlen); + if (s == NULL) + return NULL; /* Make sure added region doesn't contain garbage */ - memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ + memset(s + curlen, 0, (len - curlen + 1)); /* also set trailing \0 byte */ sdssetlen(s, len); return s; } @@ -381,11 +399,12 @@ sds sdsgrowzero(sds s, size_t len) { sds sdscatlen(sds s, const void *t, size_t len) { size_t curlen = sdslen(s); - s = sdsMakeRoomFor(s,len); - if (s == NULL) return NULL; - memcpy(s+curlen, t, len); - sdssetlen(s, curlen+len); - s[curlen+len] = '\0'; + s = sdsMakeRoomFor(s, len); + if (s == NULL) + return NULL; + memcpy(s + curlen, t, len); + sdssetlen(s, curlen + len); + s[curlen + len] = '\0'; return s; } @@ -409,8 +428,9 @@ sds sdscatsds(sds s, const sds t) { * safe string pointed by 't' of length 'len' bytes. */ sds sdscpylen(sds s, const char *t, size_t len) { if (sdsalloc(s) < len) { - s = sdsMakeRoomFor(s,len-sdslen(s)); - if (s == NULL) return NULL; + s = sdsMakeRoomFor(s, len - sdslen(s)); + if (s == NULL) + return NULL; } memcpy(s, t, len); s[len] = '\0'; @@ -441,18 +461,19 @@ int sdsll2str(char *s, long long value) { v = (value < 0) ? -value : value; p = s; do { - *p++ = '0'+(v%10); + *p++ = '0' + (v % 10); v /= 10; - } while(v); - if (value < 0) *p++ = '-'; + } while (v); + if (value < 0) + *p++ = '-'; /* Compute length and add null term. */ - l = p-s; + l = p - s; *p = '\0'; /* Reverse the string. */ p--; - while(s < p) { + while (s < p) { aux = *s; *s = *p; *p = aux; @@ -471,17 +492,17 @@ int sdsull2str(char *s, unsigned long long v) { * an reversed string. */ p = s; do { - *p++ = '0'+(v%10); + *p++ = '0' + (v % 10); v /= 10; - } while(v); + } while (v); /* Compute length and add null term. */ - l = p-s; + l = p - s; *p = '\0'; /* Reverse the string. */ p--; - while(s < p) { + while (s < p) { aux = *s; *s = *p; *p = aux; @@ -497,38 +518,41 @@ int sdsull2str(char *s, unsigned long long v) { */ sds sdsfromlonglong(long long value) { char buf[SDS_LLSTR_SIZE]; - int len = sdsll2str(buf,value); + int len = sdsll2str(buf, value); - return sdsnewlen(buf,len); + return sdsnewlen(buf, len); } /* Like sdscatprintf() but gets va_list instead of being variadic. */ sds sdscatvprintf(sds s, const char *fmt, va_list ap) { va_list cpy; char staticbuf[1024], *buf = staticbuf, *t; - size_t buflen = strlen(fmt)*2; + size_t buflen = strlen(fmt) * 2; /* We try to start using a static buffer for speed. * If not possible we revert to heap allocation. */ if (buflen > sizeof(staticbuf)) { buf = s_malloc(buflen); - if (buf == NULL) return NULL; + if (buf == NULL) + return NULL; } else { buflen = sizeof(staticbuf); } /* Try with buffers two times bigger every time we fail to * fit the string in the current buffer size. */ - while(1) { - buf[buflen-2] = '\0'; - va_copy(cpy,ap); + while (1) { + buf[buflen - 2] = '\0'; + va_copy(cpy, ap); vsnprintf(buf, buflen, fmt, cpy); va_end(cpy); - if (buf[buflen-2] != '\0') { - if (buf != staticbuf) s_free(buf); + if (buf[buflen - 2] != '\0') { + if (buf != staticbuf) + s_free(buf); buflen *= 2; buf = s_malloc(buflen); - if (buf == NULL) return NULL; + if (buf == NULL) + return NULL; continue; } break; @@ -536,7 +560,8 @@ sds sdscatvprintf(sds s, const char *fmt, va_list ap) { /* Finally concat the obtained string to the SDS string and return it. */ t = sdscat(s, buf); - if (buf != staticbuf) s_free(buf); + if (buf != staticbuf) + s_free(buf); return t; } @@ -560,7 +585,7 @@ sds sdscatprintf(sds s, const char *fmt, ...) { va_list ap; char *t; va_start(ap, fmt); - t = sdscatvprintf(s,fmt,ap); + t = sdscatvprintf(s, fmt, ap); va_end(ap); return t; } @@ -586,82 +611,86 @@ sds sdscatfmt(sds s, char const *fmt, ...) { long i; va_list ap; - va_start(ap,fmt); + va_start(ap, fmt); i = sdslen(s); /* Position of the next byte to write to dest str. */ - while(*f) { + while (*f) { char next, *str; size_t l; long long num; unsigned long long unum; /* Make sure there is always space for at least 1 char. */ - if (sdsavail(s)==0) { - s = sdsMakeRoomFor(s,1); - if (s == NULL) goto fmt_error; + if (sdsavail(s) == 0) { + s = sdsMakeRoomFor(s, 1); + if (s == NULL) + goto fmt_error; } - switch(*f) { + switch (*f) { case '%': - next = *(f+1); + next = *(f + 1); f++; - switch(next) { + switch (next) { case 's': case 'S': - str = va_arg(ap,char*); + str = va_arg(ap, char *); l = (next == 's') ? strlen(str) : sdslen(str); if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - if (s == NULL) goto fmt_error; + s = sdsMakeRoomFor(s, l); + if (s == NULL) + goto fmt_error; } - memcpy(s+i,str,l); - sdsinclen(s,l); + memcpy(s + i, str, l); + sdsinclen(s, l); i += l; break; case 'i': case 'I': if (next == 'i') - num = va_arg(ap,int); + num = va_arg(ap, int); else - num = va_arg(ap,long long); + num = va_arg(ap, long long); { char buf[SDS_LLSTR_SIZE]; - l = sdsll2str(buf,num); + l = sdsll2str(buf, num); if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - if (s == NULL) goto fmt_error; + s = sdsMakeRoomFor(s, l); + if (s == NULL) + goto fmt_error; } - memcpy(s+i,buf,l); - sdsinclen(s,l); + memcpy(s + i, buf, l); + sdsinclen(s, l); i += l; } break; case 'u': case 'U': if (next == 'u') - unum = va_arg(ap,unsigned int); + unum = va_arg(ap, unsigned int); else - unum = va_arg(ap,unsigned long long); + unum = va_arg(ap, unsigned long long); { char buf[SDS_LLSTR_SIZE]; - l = sdsull2str(buf,unum); + l = sdsull2str(buf, unum); if (sdsavail(s) < l) { - s = sdsMakeRoomFor(s,l); - if (s == NULL) goto fmt_error; + s = sdsMakeRoomFor(s, l); + if (s == NULL) + goto fmt_error; } - memcpy(s+i,buf,l); - sdsinclen(s,l); + memcpy(s + i, buf, l); + sdsinclen(s, l); i += l; } break; default: /* Handle %% and generally %. */ s[i++] = next; - sdsinclen(s,1); + sdsinclen(s, 1); break; } break; default: s[i++] = *f; - sdsinclen(s,1); + sdsinclen(s, 1); break; } f++; @@ -696,13 +725,16 @@ sds sdstrim(sds s, const char *cset) { size_t len; sp = s; - ep = end = s+sdslen(s)-1; - while(sp <= end && strchr(cset, *sp)) sp++; - while(ep > sp && strchr(cset, *ep)) ep--; - len = (sp > ep) ? 0 : ((ep-sp)+1); - if (s != sp) memmove(s, sp, len); + ep = end = s + sdslen(s) - 1; + while (sp <= end && strchr(cset, *sp)) + sp++; + while (ep > sp && strchr(cset, *ep)) + ep--; + len = (sp > ep) ? 0 : ((ep - sp) + 1); + if (s != sp) + memmove(s, sp, len); s[len] = '\0'; - sdssetlen(s,len); + sdssetlen(s, len); return s; } @@ -728,31 +760,36 @@ sds sdstrim(sds s, const char *cset) { */ int sdsrange(sds s, ssize_t start, ssize_t end) { size_t newlen, len = sdslen(s); - if (len > SSIZE_MAX) return -1; + if (len > SSIZE_MAX) + return -1; - if (len == 0) return 0; + if (len == 0) + return 0; if (start < 0) { - start = len+start; - if (start < 0) start = 0; + start = len + start; + if (start < 0) + start = 0; } if (end < 0) { - end = len+end; - if (end < 0) end = 0; + end = len + end; + if (end < 0) + end = 0; } - newlen = (start > end) ? 0 : (end-start)+1; + newlen = (start > end) ? 0 : (end - start) + 1; if (newlen != 0) { if (start >= (ssize_t)len) { newlen = 0; } else if (end >= (ssize_t)len) { - end = len-1; - newlen = (start > end) ? 0 : (end-start)+1; + end = len - 1; + newlen = (start > end) ? 0 : (end - start) + 1; } } else { start = 0; } - if (start && newlen) memmove(s, s+start, newlen); + if (start && newlen) + memmove(s, s + start, newlen); s[newlen] = 0; - sdssetlen(s,newlen); + sdssetlen(s, newlen); return 0; } @@ -760,14 +797,16 @@ int sdsrange(sds s, ssize_t start, ssize_t end) { void sdstolower(sds s) { size_t len = sdslen(s), j; - for (j = 0; j < len; j++) s[j] = tolower(s[j]); + for (j = 0; j < len; j++) + s[j] = tolower(s[j]); } /* Apply toupper() to every character of the sds string 's'. */ void sdstoupper(sds s) { size_t len = sdslen(s), j; - for (j = 0; j < len; j++) s[j] = toupper(s[j]); + for (j = 0; j < len; j++) + s[j] = toupper(s[j]); } /* Compare two sds strings s1 and s2 with memcmp(). @@ -788,8 +827,9 @@ int sdscmp(const sds s1, const sds s2) { l1 = sdslen(s1); l2 = sdslen(s2); minlen = (l1 < l2) ? l1 : l2; - cmp = memcmp(s1,s2,minlen); - if (cmp == 0) return l1-l2; + cmp = memcmp(s1, s2, minlen); + if (cmp == 0) + return l1 - l2; return cmp; } @@ -813,55 +853,61 @@ sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count int elements = 0, slots = 5, start = 0, j; sds *tokens; - if (seplen < 1 || len < 0) return NULL; + if (seplen < 1 || len < 0) + return NULL; - tokens = s_malloc(sizeof(sds)*slots); - if (tokens == NULL) return NULL; + tokens = s_malloc(sizeof(sds) * slots); + if (tokens == NULL) + return NULL; if (len == 0) { *count = 0; return tokens; } - for (j = 0; j < (len-(seplen-1)); j++) { + for (j = 0; j < (len - (seplen - 1)); j++) { /* make sure there is room for the next element and the final one */ - if (slots < elements+2) { + if (slots < elements + 2) { sds *newtokens; slots *= 2; - newtokens = s_realloc(tokens,sizeof(sds)*slots); - if (newtokens == NULL) goto cleanup; + newtokens = s_realloc(tokens, sizeof(sds) * slots); + if (newtokens == NULL) + goto cleanup; tokens = newtokens; } /* search the separator */ - if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { - tokens[elements] = sdsnewlen(s+start,j-start); - if (tokens[elements] == NULL) goto cleanup; + if ((seplen == 1 && *(s + j) == sep[0]) || (memcmp(s + j, sep, seplen) == 0)) { + tokens[elements] = sdsnewlen(s + start, j - start); + if (tokens[elements] == NULL) + goto cleanup; elements++; - start = j+seplen; - j = j+seplen-1; /* skip the separator */ + start = j + seplen; + j = j + seplen - 1; /* skip the separator */ } } /* Add the final element. We are sure there is room in the tokens array. */ - tokens[elements] = sdsnewlen(s+start,len-start); - if (tokens[elements] == NULL) goto cleanup; + tokens[elements] = sdsnewlen(s + start, len - start); + if (tokens[elements] == NULL) + goto cleanup; elements++; *count = elements; return tokens; -cleanup: - { - int i; - for (i = 0; i < elements; i++) sdsfree(tokens[i]); - s_free(tokens); - *count = 0; - return NULL; - } +cleanup: { + int i; + for (i = 0; i < elements; i++) + sdsfree(tokens[i]); + s_free(tokens); + *count = 0; + return NULL; +} } /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ void sdsfreesplitres(sds *tokens, int count) { - if (!tokens) return; - while(count--) + if (!tokens) + return; + while (count--) sdsfree(tokens[count]); s_free(tokens); } @@ -873,51 +919,84 @@ void sdsfreesplitres(sds *tokens, int count) { * After the call, the modified sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdscatrepr(sds s, const char *p, size_t len) { - s = sdscatlen(s,"\"",1); - while(len--) { - switch(*p) { + s = sdscatlen(s, "\"", 1); + while (len--) { + switch (*p) { case '\\': case '"': - s = sdscatprintf(s,"\\%c",*p); + s = sdscatprintf(s, "\\%c", *p); + break; + case '\n': + s = sdscatlen(s, "\\n", 2); + break; + case '\r': + s = sdscatlen(s, "\\r", 2); + break; + case '\t': + s = sdscatlen(s, "\\t", 2); + break; + case '\a': + s = sdscatlen(s, "\\a", 2); + break; + case '\b': + s = sdscatlen(s, "\\b", 2); break; - case '\n': s = sdscatlen(s,"\\n",2); break; - case '\r': s = sdscatlen(s,"\\r",2); break; - case '\t': s = sdscatlen(s,"\\t",2); break; - case '\a': s = sdscatlen(s,"\\a",2); break; - case '\b': s = sdscatlen(s,"\\b",2); break; default: - if (isprint((int) *p)) - s = sdscatprintf(s,"%c",*p); + if (isprint((int)*p)) + s = sdscatprintf(s, "%c", *p); else - s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); + s = sdscatprintf(s, "\\x%02x", (unsigned char)*p); break; } p++; } - return sdscatlen(s,"\"",1); + return sdscatlen(s, "\"", 1); } /* Helper function for sdssplitargs() that converts a hex digit into an * integer from 0 to 15 */ int hex_digit_to_int(char c) { - switch(c) { - case '0': return 0; - case '1': return 1; - case '2': return 2; - case '3': return 3; - case '4': return 4; - case '5': return 5; - case '6': return 6; - case '7': return 7; - case '8': return 8; - case '9': return 9; - case 'a': case 'A': return 10; - case 'b': case 'B': return 11; - case 'c': case 'C': return 12; - case 'd': case 'D': return 13; - case 'e': case 'E': return 14; - case 'f': case 'F': return 15; - default: return 0; + switch (c) { + case '0': + return 0; + case '1': + return 1; + case '2': + return 2; + case '3': + return 3; + case '4': + return 4; + case '5': + return 5; + case '6': + return 6; + case '7': + return 7; + case '8': + return 8; + case '9': + return 9; + case 'a': + case 'A': + return 10; + case 'b': + case 'B': + return 11; + case 'c': + case 'C': + return 12; + case 'd': + case 'D': + return 13; + case 'e': + case 'E': + return 14; + case 'f': + case 'F': + return 15; + default: + return 0; } } @@ -946,92 +1025,108 @@ sds *sdssplitargs(const char *line, int *argc) { char **vector = NULL; *argc = 0; - while(1) { + while (1) { /* skip blanks */ - while(*p && isspace((int) *p)) p++; + while (*p && isspace((int)*p)) + p++; if (*p) { /* get a token */ - int inq=0; /* set to 1 if we are in "quotes" */ - int insq=0; /* set to 1 if we are in 'single quotes' */ - int done=0; + int inq = 0; /* set to 1 if we are in "quotes" */ + int insq = 0; /* set to 1 if we are in 'single quotes' */ + int done = 0; - if (current == NULL) current = sdsempty(); - while(!done) { + if (current == NULL) + current = sdsempty(); + while (!done) { if (inq) { - if (*p == '\\' && *(p+1) == 'x' && - isxdigit((int) *(p+2)) && - isxdigit((int) *(p+3))) - { + if (*p == '\\' && *(p + 1) == 'x' && + isxdigit((int)*(p + 2)) && + isxdigit((int)*(p + 3))) { unsigned char byte; - byte = (hex_digit_to_int(*(p+2))*16)+ - hex_digit_to_int(*(p+3)); - current = sdscatlen(current,(char*)&byte,1); + byte = (hex_digit_to_int(*(p + 2)) * 16) + + hex_digit_to_int(*(p + 3)); + current = sdscatlen(current, (char *)&byte, 1); p += 3; - } else if (*p == '\\' && *(p+1)) { + } else if (*p == '\\' && *(p + 1)) { char c; p++; - switch(*p) { - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'b': c = '\b'; break; - case 'a': c = '\a'; break; - default: c = *p; break; + switch (*p) { + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'b': + c = '\b'; + break; + case 'a': + c = '\a'; + break; + default: + c = *p; + break; } - current = sdscatlen(current,&c,1); + current = sdscatlen(current, &c, 1); } else if (*p == '"') { /* closing quote must be followed by a space or * nothing at all. */ - if (*(p+1) && !isspace((int) *(p+1))) goto err; - done=1; + if (*(p + 1) && !isspace((int)*(p + 1))) + goto err; + done = 1; } else if (!*p) { /* unterminated quotes */ goto err; } else { - current = sdscatlen(current,p,1); + current = sdscatlen(current, p, 1); } } else if (insq) { - if (*p == '\\' && *(p+1) == '\'') { + if (*p == '\\' && *(p + 1) == '\'') { p++; - current = sdscatlen(current,"'",1); + current = sdscatlen(current, "'", 1); } else if (*p == '\'') { /* closing quote must be followed by a space or * nothing at all. */ - if (*(p+1) && !isspace((int) *(p+1))) goto err; - done=1; + if (*(p + 1) && !isspace((int)*(p + 1))) + goto err; + done = 1; } else if (!*p) { /* unterminated quotes */ goto err; } else { - current = sdscatlen(current,p,1); + current = sdscatlen(current, p, 1); } } else { - switch(*p) { + switch (*p) { case ' ': case '\n': case '\r': case '\t': case '\0': - done=1; + done = 1; break; case '"': - inq=1; + inq = 1; break; case '\'': - insq=1; + insq = 1; break; default: - current = sdscatlen(current,p,1); + current = sdscatlen(current, p, 1); break; } } - if (*p) p++; + if (*p) + p++; } /* add the token to the vector */ { - char **new_vector = s_realloc(vector,((*argc)+1)*sizeof(char*)); + char **new_vector = s_realloc(vector, ((*argc) + 1) * sizeof(char *)); if (new_vector == NULL) { s_free(vector); return NULL; @@ -1044,16 +1139,18 @@ sds *sdssplitargs(const char *line, int *argc) { } } else { /* Even on empty input string return something not NULL. */ - if (vector == NULL) vector = s_malloc(sizeof(void*)); + if (vector == NULL) + vector = s_malloc(sizeof(void *)); return vector; } } err: - while((*argc)--) + while ((*argc)--) sdsfree(vector[*argc]); s_free(vector); - if (current) sdsfree(current); + if (current) + sdsfree(current); *argc = 0; return NULL; } @@ -1089,7 +1186,8 @@ sds sdsjoin(char **argv, int argc, char *sep) { for (j = 0; j < argc; j++) { join = sdscat(join, argv[j]); - if (j != argc-1) join = sdscat(join,sep); + if (j != argc - 1) + join = sdscat(join, sep); } return join; } @@ -1101,7 +1199,8 @@ sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) { for (j = 0; j < argc; j++) { join = sdscatsds(join, argv[j]); - if (j != argc-1) join = sdscatlen(join,sep,seplen); + if (j != argc - 1) + join = sdscatlen(join, sep, seplen); } return join; } @@ -1112,13 +1211,14 @@ sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) { * the programs SDS is linked to, if they want to touch the SDS internals * even if they use a different allocator. */ void *sds_malloc(size_t size) { return s_malloc(size); } -void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); } +void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr, size); } void sds_free(void *ptr) { s_free(ptr); } #if defined(SDS_TEST_MAIN) -#include -#include "testhelp.h" #include "limits.h" +#include "testhelp.h" + +#include #define UNUSED(x) (void)(x) int sdsTest(void) { @@ -1126,124 +1226,125 @@ int sdsTest(void) { sds x = sdsnew("foo"), y; test_cond("Create a string and obtain the length", - sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) + sdslen(x) == 3 && memcmp(x, "foo\0", 4) == 0); sdsfree(x); - x = sdsnewlen("foo",2); + x = sdsnewlen("foo", 2); test_cond("Create a string with specified length", - sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) + sdslen(x) == 2 && memcmp(x, "fo\0", 3) == 0); - x = sdscat(x,"bar"); + x = sdscat(x, "bar"); test_cond("Strings concatenation", - sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); + sdslen(x) == 5 && memcmp(x, "fobar\0", 6) == 0); - x = sdscpy(x,"a"); + x = sdscpy(x, "a"); test_cond("sdscpy() against an originally longer string", - sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) + sdslen(x) == 1 && memcmp(x, "a\0", 2) == 0); - x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); + x = sdscpy(x, "xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); test_cond("sdscpy() against an originally shorter string", - sdslen(x) == 33 && - memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) + sdslen(x) == 33 && + memcmp(x, "xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0", 33) == 0); sdsfree(x); - x = sdscatprintf(sdsempty(),"%d",123); + x = sdscatprintf(sdsempty(), "%d", 123); test_cond("sdscatprintf() seems working in the base case", - sdslen(x) == 3 && memcmp(x,"123\0",4) == 0) + sdslen(x) == 3 && memcmp(x, "123\0", 4) == 0); sdsfree(x); x = sdsnew("--"); - x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX); + x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN, LLONG_MAX); test_cond("sdscatfmt() seems working in the base case", - sdslen(x) == 60 && - memcmp(x,"--Hello Hi! World -9223372036854775808," - "9223372036854775807--",60) == 0) - printf("[%s]\n",x); + sdslen(x) == 60 && + memcmp(x, "--Hello Hi! World -9223372036854775808," + "9223372036854775807--", + 60) == 0); + printf("[%s]\n", x); sdsfree(x); x = sdsnew("--"); x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX); test_cond("sdscatfmt() seems working with unsigned numbers", - sdslen(x) == 35 && - memcmp(x,"--4294967295,18446744073709551615--",35) == 0) + sdslen(x) == 35 && + memcmp(x, "--4294967295,18446744073709551615--", 35) == 0); sdsfree(x); x = sdsnew(" x "); - sdstrim(x," x"); + sdstrim(x, " x"); test_cond("sdstrim() works when all chars match", - sdslen(x) == 0) + sdslen(x) == 0) - sdsfree(x); + sdsfree(x); x = sdsnew(" x "); - sdstrim(x," "); + sdstrim(x, " "); test_cond("sdstrim() works when a single char remains", - sdslen(x) == 1 && x[0] == 'x') + sdslen(x) == 1 && x[0] == 'x') - sdsfree(x); + sdsfree(x); x = sdsnew("xxciaoyyy"); - sdstrim(x,"xy"); + sdstrim(x, "xy"); test_cond("sdstrim() correctly trims characters", - sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) + sdslen(x) == 4 && memcmp(x, "ciao\0", 5) == 0); y = sdsdup(x); - sdsrange(y,1,1); + sdsrange(y, 1, 1); test_cond("sdsrange(...,1,1)", - sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) + sdslen(y) == 1 && memcmp(y, "i\0", 2) == 0); sdsfree(y); y = sdsdup(x); - sdsrange(y,1,-1); + sdsrange(y, 1, -1); test_cond("sdsrange(...,1,-1)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) + sdslen(y) == 3 && memcmp(y, "iao\0", 4) == 0); sdsfree(y); y = sdsdup(x); - sdsrange(y,-2,-1); + sdsrange(y, -2, -1); test_cond("sdsrange(...,-2,-1)", - sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) + sdslen(y) == 2 && memcmp(y, "ao\0", 3) == 0); sdsfree(y); y = sdsdup(x); - sdsrange(y,2,1); + sdsrange(y, 2, 1); test_cond("sdsrange(...,2,1)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) + sdslen(y) == 0 && memcmp(y, "\0", 1) == 0); sdsfree(y); y = sdsdup(x); - sdsrange(y,1,100); + sdsrange(y, 1, 100); test_cond("sdsrange(...,1,100)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) + sdslen(y) == 3 && memcmp(y, "iao\0", 4) == 0); sdsfree(y); y = sdsdup(x); - sdsrange(y,100,100); + sdsrange(y, 100, 100); test_cond("sdsrange(...,100,100)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) + sdslen(y) == 0 && memcmp(y, "\0", 1) == 0); sdsfree(y); sdsfree(x); x = sdsnew("foo"); y = sdsnew("foa"); - test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) + test_cond("sdscmp(foo,foa)", sdscmp(x, y) > 0); sdsfree(y); sdsfree(x); x = sdsnew("bar"); y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) + test_cond("sdscmp(bar,bar)", sdscmp(x, y) == 0); sdsfree(y); sdsfree(x); x = sdsnew("aar"); y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) + test_cond("sdscmp(bar,bar)", sdscmp(x, y) < 0); sdsfree(y); sdsfree(x); - x = sdsnewlen("\a\n\0foo\r",7); - y = sdscatrepr(sdsempty(),x,sdslen(x)); + x = sdsnewlen("\a\n\0foo\r", 7); + y = sdscatrepr(sdsempty(), x, sdslen(x)); test_cond("sdscatrepr(...data...)", - memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0) + memcmp(y, "\"\\a\\n\\x00foo\\r\"", 15) == 0); { unsigned int oldfree; @@ -1259,28 +1360,28 @@ int sdsTest(void) { * SDS header types. */ for (i = 0; i < 10; i++) { int oldlen = sdslen(x); - x = sdsMakeRoomFor(x,step); - int type = x[-1]&SDS_TYPE_MASK; + x = sdsMakeRoomFor(x, step); + int type = x[-1] & SDS_TYPE_MASK; test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen); if (type != SDS_TYPE_5) { test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step); oldfree = sdsavail(x); } - p = x+oldlen; + p = x + oldlen; for (j = 0; j < step; j++) { - p[j] = 'A'+j; + p[j] = 'A' + j; } - sdsIncrLen(x,step); + sdsIncrLen(x, step); } test_cond("sdsMakeRoomFor() content", - memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0); - test_cond("sdsMakeRoomFor() final length",sdslen(x)==101); + memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ", x, 101) == 0); + test_cond("sdsMakeRoomFor() final length", sdslen(x) == 101); sdsfree(x); } } - test_report() + test_report(); return 0; } #endif diff --git a/src/sockcompat.c b/src/sockcompat.c index 20ad8c60..9dff18a8 100644 --- a/src/sockcompat.c +++ b/src/sockcompat.c @@ -34,63 +34,63 @@ #ifdef _WIN32 static int _wsaErrorToErrno(int err) { switch (err) { - case WSAEWOULDBLOCK: - return EWOULDBLOCK; - case WSAEINPROGRESS: - return EINPROGRESS; - case WSAEALREADY: - return EALREADY; - case WSAENOTSOCK: - return ENOTSOCK; - case WSAEDESTADDRREQ: - return EDESTADDRREQ; - case WSAEMSGSIZE: - return EMSGSIZE; - case WSAEPROTOTYPE: - return EPROTOTYPE; - case WSAENOPROTOOPT: - return ENOPROTOOPT; - case WSAEPROTONOSUPPORT: - return EPROTONOSUPPORT; - case WSAEOPNOTSUPP: - return EOPNOTSUPP; - case WSAEAFNOSUPPORT: - return EAFNOSUPPORT; - case WSAEADDRINUSE: - return EADDRINUSE; - case WSAEADDRNOTAVAIL: - return EADDRNOTAVAIL; - case WSAENETDOWN: - return ENETDOWN; - case WSAENETUNREACH: - return ENETUNREACH; - case WSAENETRESET: - return ENETRESET; - case WSAECONNABORTED: - return ECONNABORTED; - case WSAECONNRESET: - return ECONNRESET; - case WSAENOBUFS: - return ENOBUFS; - case WSAEISCONN: - return EISCONN; - case WSAENOTCONN: - return ENOTCONN; - case WSAETIMEDOUT: - return ETIMEDOUT; - case WSAECONNREFUSED: - return ECONNREFUSED; - case WSAELOOP: - return ELOOP; - case WSAENAMETOOLONG: - return ENAMETOOLONG; - case WSAEHOSTUNREACH: - return EHOSTUNREACH; - case WSAENOTEMPTY: - return ENOTEMPTY; - default: - /* We just return a generic I/O error if we could not find a relevant error. */ - return EIO; + case WSAEWOULDBLOCK: + return EWOULDBLOCK; + case WSAEINPROGRESS: + return EINPROGRESS; + case WSAEALREADY: + return EALREADY; + case WSAENOTSOCK: + return ENOTSOCK; + case WSAEDESTADDRREQ: + return EDESTADDRREQ; + case WSAEMSGSIZE: + return EMSGSIZE; + case WSAEPROTOTYPE: + return EPROTOTYPE; + case WSAENOPROTOOPT: + return ENOPROTOOPT; + case WSAEPROTONOSUPPORT: + return EPROTONOSUPPORT; + case WSAEOPNOTSUPP: + return EOPNOTSUPP; + case WSAEAFNOSUPPORT: + return EAFNOSUPPORT; + case WSAEADDRINUSE: + return EADDRINUSE; + case WSAEADDRNOTAVAIL: + return EADDRNOTAVAIL; + case WSAENETDOWN: + return ENETDOWN; + case WSAENETUNREACH: + return ENETUNREACH; + case WSAENETRESET: + return ENETRESET; + case WSAECONNABORTED: + return ECONNABORTED; + case WSAECONNRESET: + return ECONNRESET; + case WSAENOBUFS: + return ENOBUFS; + case WSAEISCONN: + return EISCONN; + case WSAENOTCONN: + return ENOTCONN; + case WSAETIMEDOUT: + return ETIMEDOUT; + case WSAECONNREFUSED: + return ECONNREFUSED; + case WSAELOOP: + return ELOOP; + case WSAENAMETOOLONG: + return ENAMETOOLONG; + case WSAEHOSTUNREACH: + return EHOSTUNREACH; + case WSAENOTEMPTY: + return ENOTEMPTY; + default: + /* We just return a generic I/O error if we could not find a relevant error. */ + return EIO; } } @@ -102,7 +102,7 @@ static int _initWinsock() { static int s_initialized = 0; if (!s_initialized) { static WSADATA wsadata; - int err = WSAStartup(MAKEWORD(2,2), &wsadata); + int err = WSAStartup(MAKEWORD(2, 2), &wsadata); if (err != 0) { errno = _wsaErrorToErrno(err); return 0; @@ -119,29 +119,56 @@ int win32_getaddrinfo(const char *node, const char *service, const struct addrin } switch (getaddrinfo(node, service, hints, res)) { - case 0: return 0; - case WSATRY_AGAIN: return EAI_AGAIN; - case WSAEINVAL: return EAI_BADFLAGS; - case WSAEAFNOSUPPORT: return EAI_FAMILY; - case WSA_NOT_ENOUGH_MEMORY: return EAI_MEMORY; - case WSAHOST_NOT_FOUND: return EAI_NONAME; - case WSATYPE_NOT_FOUND: return EAI_SERVICE; - case WSAESOCKTNOSUPPORT: return EAI_SOCKTYPE; - default: return EAI_FAIL; /* Including WSANO_RECOVERY */ + case 0: + return 0; + case WSATRY_AGAIN: + return EAI_AGAIN; + case WSAEINVAL: + return EAI_BADFLAGS; + case WSAEAFNOSUPPORT: + return EAI_FAMILY; + case WSA_NOT_ENOUGH_MEMORY: + return EAI_MEMORY; + case WSAHOST_NOT_FOUND: + return EAI_NONAME; + case WSATYPE_NOT_FOUND: + return EAI_SERVICE; + case WSAESOCKTNOSUPPORT: + return EAI_SOCKTYPE; + default: + return EAI_FAIL; /* Including WSANO_RECOVERY */ } } const char *win32_gai_strerror(int errcode) { switch (errcode) { - case 0: errcode = 0; break; - case EAI_AGAIN: errcode = WSATRY_AGAIN; break; - case EAI_BADFLAGS: errcode = WSAEINVAL; break; - case EAI_FAMILY: errcode = WSAEAFNOSUPPORT; break; - case EAI_MEMORY: errcode = WSA_NOT_ENOUGH_MEMORY; break; - case EAI_NONAME: errcode = WSAHOST_NOT_FOUND; break; - case EAI_SERVICE: errcode = WSATYPE_NOT_FOUND; break; - case EAI_SOCKTYPE: errcode = WSAESOCKTNOSUPPORT; break; - default: errcode = WSANO_RECOVERY; break; /* Including EAI_FAIL */ + case 0: + errcode = 0; + break; + case EAI_AGAIN: + errcode = WSATRY_AGAIN; + break; + case EAI_BADFLAGS: + errcode = WSAEINVAL; + break; + case EAI_FAMILY: + errcode = WSAEAFNOSUPPORT; + break; + case EAI_MEMORY: + errcode = WSA_NOT_ENOUGH_MEMORY; + break; + case EAI_NONAME: + errcode = WSAHOST_NOT_FOUND; + break; + case EAI_SERVICE: + errcode = WSATYPE_NOT_FOUND; + break; + case EAI_SOCKTYPE: + errcode = WSAESOCKTNOSUPPORT; + break; + default: + errcode = WSANO_RECOVERY; + break; /* Including EAI_FAIL */ } return gai_strerror(errcode); } @@ -187,8 +214,7 @@ int win32_connect(SOCKET sockfd, const struct sockaddr *addr, socklen_t addrlen) int err = errno; if (err == EWOULDBLOCK) { errno = EINPROGRESS; - } - else if (err == EIO) { + } else if (err == EIO) { errno = EALREADY; } @@ -198,7 +224,7 @@ int win32_connect(SOCKET sockfd, const struct sockaddr *addr, socklen_t addrlen) int win32_getsockopt(SOCKET sockfd, int level, int optname, void *optval, socklen_t *optlen) { int ret = 0; if ((level == SOL_SOCKET) && ((optname == SO_RCVTIMEO) || (optname == SO_SNDTIMEO))) { - if (*optlen >= sizeof (struct timeval)) { + if (*optlen >= sizeof(struct timeval)) { struct timeval *tv = optval; DWORD timeout = 0; socklen_t dwlen = 0; @@ -208,16 +234,16 @@ int win32_getsockopt(SOCKET sockfd, int level, int optname, void *optval, sockle } else { ret = WSAEFAULT; } - *optlen = sizeof (struct timeval); + *optlen = sizeof(struct timeval); } else { - ret = getsockopt(sockfd, level, optname, (char*)optval, optlen); + ret = getsockopt(sockfd, level, optname, (char *)optval, optlen); } if (ret != SOCKET_ERROR && level == SOL_SOCKET && optname == SO_ERROR) { /* translate SO_ERROR codes, if non-zero */ - int err = *(int*)optval; + int err = *(int *)optval; if (err != 0) { err = _wsaErrorToErrno(err); - *(int*)optval = err; + *(int *)optval = err; } } _updateErrno(ret != SOCKET_ERROR); @@ -229,9 +255,9 @@ int win32_setsockopt(SOCKET sockfd, int level, int optname, const void *optval, if ((level == SOL_SOCKET) && ((optname == SO_RCVTIMEO) || (optname == SO_SNDTIMEO))) { const struct timeval *tv = optval; DWORD timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000; - ret = setsockopt(sockfd, level, optname, (const char*)&timeout, sizeof(DWORD)); + ret = setsockopt(sockfd, level, optname, (const char *)&timeout, sizeof(DWORD)); } else { - ret = setsockopt(sockfd, level, optname, (const char*)optval, optlen); + ret = setsockopt(sockfd, level, optname, (const char *)optval, optlen); } _updateErrno(ret != SOCKET_ERROR); return ret != SOCKET_ERROR ? ret : -1; @@ -244,13 +270,13 @@ int win32_close(SOCKET fd) { } ssize_t win32_recv(SOCKET sockfd, void *buf, size_t len, int flags) { - int ret = recv(sockfd, (char*)buf, (int)len, flags); + int ret = recv(sockfd, (char *)buf, (int)len, flags); _updateErrno(ret != SOCKET_ERROR); return ret != SOCKET_ERROR ? ret : -1; } ssize_t win32_send(SOCKET sockfd, const void *buf, size_t len, int flags) { - int ret = send(sockfd, (const char*)buf, (int)len, flags); + int ret = send(sockfd, (const char *)buf, (int)len, flags); _updateErrno(ret != SOCKET_ERROR); return ret != SOCKET_ERROR ? ret : -1; } diff --git a/src/ssl.c b/src/ssl.c index 904c8f41..8456393f 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -30,16 +30,16 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "valkey.h" #include "async.h" #include "net.h" +#include "valkey.h" #include #include #include #ifdef _WIN32 -#include #include +#include #ifdef OPENSSL_IS_BORINGSSL #undef X509_NAME #undef X509_EXTENSIONS @@ -52,13 +52,14 @@ #include #endif -#include -#include - #include "win32.h" + #include "async_private.h" -#include "valkey_ssl.h" #include "valkey_private.h" +#include "valkey_ssl.h" + +#include +#include #define OPENSSL_1_1_0 0x10100000L @@ -108,13 +109,13 @@ static valkeyContextFuncs valkeyContextSSLFuncs; #ifdef VALKEY_USE_CRYPTO_LOCKS #ifdef _WIN32 typedef CRITICAL_SECTION sslLockType; -static void sslLockInit(sslLockType* l) { +static void sslLockInit(sslLockType *l) { InitializeCriticalSection(l); } -static void sslLockAcquire(sslLockType* l) { +static void sslLockAcquire(sslLockType *l) { EnterCriticalSection(l); } -static void sslLockRelease(sslLockType* l) { +static void sslLockRelease(sslLockType *l) { LeaveCriticalSection(l); } #else @@ -130,7 +131,7 @@ static void sslLockRelease(sslLockType *l) { } #endif -static sslLockType* ossl_locks; +static sslLockType *ossl_locks; static void opensslDoLock(int mode, int lkid, const char *f, int line) { sslLockType *l = ossl_locks + lkid; @@ -164,8 +165,7 @@ static int initOpensslLocks(void) { } #endif /* VALKEY_USE_CRYPTO_LOCKS */ -int valkeyInitOpenSSL(void) -{ +int valkeyInitOpenSSL(void) { SSL_library_init(); #ifdef VALKEY_USE_CRYPTO_LOCKS initOpensslLocks(); @@ -178,32 +178,30 @@ int valkeyInitOpenSSL(void) * valkeySSLContext helper context destruction. */ -const char *valkeySSLContextGetError(valkeySSLContextError error) -{ +const char *valkeySSLContextGetError(valkeySSLContextError error) { switch (error) { - case VALKEY_SSL_CTX_NONE: - return "No Error"; - case VALKEY_SSL_CTX_CREATE_FAILED: - return "Failed to create OpenSSL SSL_CTX"; - case VALKEY_SSL_CTX_CERT_KEY_REQUIRED: - return "Client cert and key must both be specified or skipped"; - case VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED: - return "Failed to load CA Certificate or CA Path"; - case VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED: - return "Failed to load client certificate"; - case VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED: - return "Failed to load private key"; - case VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED: - return "Failed to open system certificate store"; - case VALKEY_SSL_CTX_OS_CERT_ADD_FAILED: - return "Failed to add CA certificates obtained from system to the SSL context"; - default: - return "Unknown error code"; + case VALKEY_SSL_CTX_NONE: + return "No Error"; + case VALKEY_SSL_CTX_CREATE_FAILED: + return "Failed to create OpenSSL SSL_CTX"; + case VALKEY_SSL_CTX_CERT_KEY_REQUIRED: + return "Client cert and key must both be specified or skipped"; + case VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED: + return "Failed to load CA Certificate or CA Path"; + case VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED: + return "Failed to load client certificate"; + case VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED: + return "Failed to load private key"; + case VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED: + return "Failed to open system certificate store"; + case VALKEY_SSL_CTX_OS_CERT_ADD_FAILED: + return "Failed to add CA certificates obtained from system to the SSL context"; + default: + return "Unknown error code"; } } -void valkeyFreeSSLContext(valkeySSLContext *ctx) -{ +void valkeyFreeSSLContext(valkeySSLContext *ctx) { if (!ctx) return; @@ -220,15 +218,13 @@ void valkeyFreeSSLContext(valkeySSLContext *ctx) vk_free(ctx); } - /** * valkeySSLContext helper context initialization. */ valkeySSLContext *valkeyCreateSSLContext(const char *cacert_filename, const char *capath, - const char *cert_filename, const char *private_key_filename, - const char *server_name, valkeySSLContextError *error) -{ + const char *cert_filename, const char *private_key_filename, + const char *server_name, valkeySSLContextError *error) { valkeySSLOptions options = { .cacert_filename = cacert_filename, .capath = capath, @@ -266,7 +262,8 @@ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, v ctx->ssl_ctx = SSL_CTX_new(ssl_method); if (!ctx->ssl_ctx) { - if (error) *error = VALKEY_SSL_CTX_CREATE_FAILED; + if (error) + *error = VALKEY_SSL_CTX_CREATE_FAILED; goto error; } @@ -279,8 +276,9 @@ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, v SSL_CTX_set_verify(ctx->ssl_ctx, options->verify_mode, NULL); if ((cert_filename != NULL && private_key_filename == NULL) || - (private_key_filename != NULL && cert_filename == NULL)) { - if (error) *error = VALKEY_SSL_CTX_CERT_KEY_REQUIRED; + (private_key_filename != NULL && cert_filename == NULL)) { + if (error) + *error = VALKEY_SSL_CTX_CERT_KEY_REQUIRED; goto error; } @@ -289,18 +287,19 @@ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, v if (0 == strcmp(cacert_filename, "wincert")) { win_store = CertOpenSystemStore(NULL, "Root"); if (!win_store) { - if (error) *error = VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED; + if (error) + *error = VALKEY_SSL_CTX_OS_CERTSTORE_OPEN_FAILED; goto error; } - X509_STORE* store = SSL_CTX_get_cert_store(ctx->ssl_ctx); + X509_STORE *store = SSL_CTX_get_cert_store(ctx->ssl_ctx); while (win_ctx = CertEnumCertificatesInStore(win_store, win_ctx)) { - X509* x509 = NULL; - x509 = d2i_X509(NULL, (const unsigned char**)&win_ctx->pbCertEncoded, win_ctx->cbCertEncoded); + X509 *x509 = NULL; + x509 = d2i_X509(NULL, (const unsigned char **)&win_ctx->pbCertEncoded, win_ctx->cbCertEncoded); if (x509) { if ((1 != X509_STORE_add_cert(store, x509)) || - (1 != SSL_CTX_add_client_CA(ctx->ssl_ctx, x509))) - { - if (error) *error = VALKEY_SSL_CTX_OS_CERT_ADD_FAILED; + (1 != SSL_CTX_add_client_CA(ctx->ssl_ctx, x509))) { + if (error) + *error = VALKEY_SSL_CTX_OS_CERT_ADD_FAILED; goto error; } X509_free(x509); @@ -310,24 +309,28 @@ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, v CertCloseStore(win_store, 0); } else #endif - if (!SSL_CTX_load_verify_locations(ctx->ssl_ctx, cacert_filename, capath)) { - if (error) *error = VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED; + if (!SSL_CTX_load_verify_locations(ctx->ssl_ctx, cacert_filename, capath)) { + if (error) + *error = VALKEY_SSL_CTX_CA_CERT_LOAD_FAILED; goto error; } } else { if (!SSL_CTX_set_default_verify_paths(ctx->ssl_ctx)) { - if (error) *error = VALKEY_SSL_CTX_CLIENT_DEFAULT_CERT_FAILED; + if (error) + *error = VALKEY_SSL_CTX_CLIENT_DEFAULT_CERT_FAILED; goto error; } } if (cert_filename) { if (!SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, cert_filename)) { - if (error) *error = VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED; + if (error) + *error = VALKEY_SSL_CTX_CLIENT_CERT_LOAD_FAILED; goto error; } if (!SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, private_key_filename, SSL_FILETYPE_PEM)) { - if (error) *error = VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED; + if (error) + *error = VALKEY_SSL_CTX_PRIVATE_KEY_LOAD_FAILED; goto error; } } @@ -350,7 +353,6 @@ valkeySSLContext *valkeyCreateSSLContextWithOptions(valkeySSLOptions *options, v * SSL Connection initialization. */ - static int valkeySSLConnect(valkeyContext *c, SSL *ssl) { if (c->privctx) { valkeySetError(c, VALKEY_ERR_OTHER, "valkeyContext was already associated"); @@ -380,8 +382,7 @@ static int valkeySSLConnect(valkeyContext *c, SSL *ssl) { rv = SSL_get_error(rssl->ssl, rv); if (((c->flags & VALKEY_BLOCK) == 0) && - (rv == SSL_ERROR_WANT_READ || rv == SSL_ERROR_WANT_WRITE)) - { + (rv == SSL_ERROR_WANT_READ || rv == SSL_ERROR_WANT_WRITE)) { c->funcs = &valkeyContextSSLFuncs; c->privctx = rssl; return VALKEY_OK; @@ -390,11 +391,11 @@ static int valkeySSLConnect(valkeyContext *c, SSL *ssl) { if (c->err == 0) { char err[512]; if (rv == SSL_ERROR_SYSCALL) - snprintf(err,sizeof(err)-1,"SSL_connect failed: %s",strerror(errno)); + snprintf(err, sizeof(err) - 1, "SSL_connect failed: %s", strerror(errno)); else { unsigned long e = ERR_peek_last_error(); - snprintf(err,sizeof(err)-1,"SSL_connect failed: %s", - ERR_reason_error_string(e)); + snprintf(err, sizeof(err) - 1, "SSL_connect failed: %s", + ERR_reason_error_string(e)); } valkeySetError(c, VALKEY_ERR_IO, err); } @@ -417,8 +418,7 @@ int valkeyInitiateSSL(valkeyContext *c, SSL *ssl) { * manage their own SSL objects. */ -int valkeyInitiateSSLWithContext(valkeyContext *c, valkeySSLContext *valkey_ssl_ctx) -{ +int valkeyInitiateSSLWithContext(valkeyContext *c, valkeySSLContext *valkey_ssl_ctx) { if (!c || !valkey_ssl_ctx) return VALKEY_ERR; @@ -473,10 +473,11 @@ static int maybeCheckWant(valkeySSL *rssl, int rv) { * Implementation of valkeyContextFuncs for SSL connections. */ -static void valkeySSLFree(void *privctx){ +static void valkeySSLFree(void *privctx) { valkeySSL *rsc = privctx; - if (!rsc) return; + if (!rsc) + return; if (rsc->ssl) { SSL_free(rsc->ssl); rsc->ssl = NULL; @@ -616,6 +617,5 @@ static valkeyContextFuncs valkeyContextSSLFuncs = { .async_write = valkeySSLAsyncWrite, .read = valkeySSLRead, .write = valkeySSLWrite, - .set_timeout = valkeyTcpSetTimeout + .set_timeout = valkeyTcpSetTimeout, }; - diff --git a/src/valkey.c b/src/valkey.c index 2119bb5c..93d4f842 100644 --- a/src/valkey.c +++ b/src/valkey.c @@ -32,17 +32,19 @@ */ #include "fmacros.h" -#include -#include -#include -#include -#include +#include "win32.h" #include "valkey.h" -#include "valkey_private.h" + #include "net.h" #include "sds.h" -#include "win32.h" +#include "valkey_private.h" + +#include +#include +#include +#include +#include static valkeyReply *createReplyObject(int type); static void *createStringObject(const valkeyReadTask *task, char *str, size_t len); @@ -61,12 +63,11 @@ static valkeyReplyObjectFunctions defaultFunctions = { createDoubleObject, createNilObject, createBoolObject, - freeReplyObject -}; + freeReplyObject}; /* Create a reply object */ static valkeyReply *createReplyObject(int type) { - valkeyReply *r = vk_calloc(1,sizeof(*r)); + valkeyReply *r = vk_calloc(1, sizeof(*r)); if (r == NULL) return NULL; @@ -83,7 +84,7 @@ void freeReplyObject(void *reply) { if (r == NULL) return; - switch(r->type) { + switch (r->type) { case VALKEY_REPLY_INTEGER: case VALKEY_REPLY_NIL: case VALKEY_REPLY_BOOL: @@ -119,27 +120,29 @@ static void *createStringObject(const valkeyReadTask *task, char *str, size_t le if (r == NULL) return NULL; - assert(task->type == VALKEY_REPLY_ERROR || + assert(task->type == VALKEY_REPLY_ERROR || task->type == VALKEY_REPLY_STATUS || task->type == VALKEY_REPLY_STRING || - task->type == VALKEY_REPLY_VERB || + task->type == VALKEY_REPLY_VERB || task->type == VALKEY_REPLY_BIGNUM); /* Copy string value */ if (task->type == VALKEY_REPLY_VERB) { - buf = vk_malloc(len-4+1); /* Skip 4 bytes of verbatim type header. */ - if (buf == NULL) goto oom; + buf = vk_malloc(len - 4 + 1); /* Skip 4 bytes of verbatim type header. */ + if (buf == NULL) + goto oom; - memcpy(r->vtype,str,3); + memcpy(r->vtype, str, 3); r->vtype[3] = '\0'; - memcpy(buf,str+4,len-4); - buf[len-4] = '\0'; + memcpy(buf, str + 4, len - 4); + buf[len - 4] = '\0'; r->len = len - 4; } else { - buf = vk_malloc(len+1); - if (buf == NULL) goto oom; + buf = vk_malloc(len + 1); + if (buf == NULL) + goto oom; - memcpy(buf,str,len); + memcpy(buf, str, len); buf[len] = '\0'; r->len = len; } @@ -169,7 +172,7 @@ static void *createArrayObject(const valkeyReadTask *task, size_t elements) { return NULL; if (elements > 0) { - r->element = vk_calloc(elements,sizeof(valkeyReply*)); + r->element = vk_calloc(elements, sizeof(valkeyReply *)); if (r->element == NULL) { freeReplyObject(r); return NULL; @@ -222,7 +225,7 @@ static void *createDoubleObject(const valkeyReadTask *task, double value, char * return NULL; r->dval = value; - r->str = vk_malloc(len+1); + r->str = vk_malloc(len + 1); if (r->str == NULL) { freeReplyObject(r); return NULL; @@ -292,28 +295,32 @@ static void *createBoolObject(const valkeyReadTask *task, int bval) { /* Return the number of digits of 'v' when converted to string in radix 10. * Implementation borrowed from link in valkey/src/util.c:string2ll(). */ static uint32_t countDigits(uint64_t v) { - uint32_t result = 1; - for (;;) { - if (v < 10) return result; - if (v < 100) return result + 1; - if (v < 1000) return result + 2; - if (v < 10000) return result + 3; - v /= 10000U; - result += 4; - } + uint32_t result = 1; + for (;;) { + if (v < 10) + return result; + if (v < 100) + return result + 1; + if (v < 1000) + return result + 2; + if (v < 10000) + return result + 3; + v /= 10000U; + result += 4; + } } /* Helper that calculates the bulk length given a certain string length. */ static size_t bulklen(size_t len) { - return 1+countDigits(len)+2+len+2; + return 1 + countDigits(len) + 2 + len + 2; } int valkeyvFormatCommand(char **target, const char *format, va_list ap) { const char *c = format; - char *cmd = NULL; /* final command */ - int pos; /* position in final command */ + char *cmd = NULL; /* final command */ + int pos; /* position in final command */ sds curarg, newarg; /* current argument */ - int touched = 0; /* was the current argument touched? */ + int touched = 0; /* was the current argument touched? */ char **curargv = NULL, **newargv = NULL; int argc = 0; int totlen = 0; @@ -329,24 +336,27 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { if (curarg == NULL) return -1; - while(*c != '\0') { + while (*c != '\0') { if (*c != '%' || c[1] == '\0') { if (*c == ' ') { if (touched) { - newargv = vk_realloc(curargv,sizeof(char*)*(argc+1)); - if (newargv == NULL) goto memory_err; + newargv = vk_realloc(curargv, sizeof(char *) * (argc + 1)); + if (newargv == NULL) + goto memory_err; curargv = newargv; curargv[argc++] = curarg; totlen += bulklen(sdslen(curarg)); /* curarg is put in argv so it can be overwritten. */ curarg = sdsempty(); - if (curarg == NULL) goto memory_err; + if (curarg == NULL) + goto memory_err; touched = 0; } } else { - newarg = sdscatlen(curarg,c,1); - if (newarg == NULL) goto memory_err; + newarg = sdscatlen(curarg, c, 1); + if (newarg == NULL) + goto memory_err; curarg = newarg; touched = 1; } @@ -357,21 +367,21 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { /* Set newarg so it can be checked even if it is not touched. */ newarg = curarg; - switch(c[1]) { + switch (c[1]) { case 's': - arg = va_arg(ap,char*); + arg = va_arg(ap, char *); size = strlen(arg); if (size > 0) - newarg = sdscatlen(curarg,arg,size); + newarg = sdscatlen(curarg, arg, size); break; case 'b': - arg = va_arg(ap,char*); - size = va_arg(ap,size_t); + arg = va_arg(ap, char *); + size = va_arg(ap, size_t); if (size > 0) - newarg = sdscatlen(curarg,arg,size); + newarg = sdscatlen(curarg, arg, size); break; case '%': - newarg = sdscat(curarg,"%"); + newarg = sdscat(curarg, "%"); break; default: /* Try to detect printf format */ @@ -379,47 +389,51 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { static const char intfmts[] = "diouxX"; static const char flags[] = "#0-+ "; char _format[16]; - const char *_p = c+1; + const char *_p = c + 1; size_t _l = 0; va_list _cpy; /* Flags */ - while (*_p != '\0' && strchr(flags,*_p) != NULL) _p++; + while (*_p != '\0' && strchr(flags, *_p) != NULL) + _p++; /* Field width */ - while (*_p != '\0' && isdigit((int) *_p)) _p++; + while (*_p != '\0' && isdigit((int)*_p)) + _p++; /* Precision */ if (*_p == '.') { _p++; - while (*_p != '\0' && isdigit((int) *_p)) _p++; + while (*_p != '\0' && isdigit((int)*_p)) + _p++; } /* Copy va_list before consuming with va_arg */ - va_copy(_cpy,ap); + va_copy(_cpy, ap); /* Make sure we have more characters otherwise strchr() accepts * '\0' as an integer specifier. This is checked after above * va_copy() to avoid UB in fmt_invalid's call to va_end(). */ - if (*_p == '\0') goto fmt_invalid; + if (*_p == '\0') + goto fmt_invalid; /* Integer conversion (without modifiers) */ - if (strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); + if (strchr(intfmts, *_p) != NULL) { + va_arg(ap, int); goto fmt_valid; } /* Double conversion (without modifiers) */ - if (strchr("eEfFgGaA",*_p) != NULL) { - va_arg(ap,double); + if (strchr("eEfFgGaA", *_p) != NULL) { + va_arg(ap, double); goto fmt_valid; } /* Size: char */ if (_p[0] == 'h' && _p[1] == 'h') { _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); /* char gets promoted to int */ + if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { + va_arg(ap, int); /* char gets promoted to int */ goto fmt_valid; } goto fmt_invalid; @@ -428,8 +442,8 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { /* Size: short */ if (_p[0] == 'h') { _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); /* short gets promoted to int */ + if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { + va_arg(ap, int); /* short gets promoted to int */ goto fmt_valid; } goto fmt_invalid; @@ -438,8 +452,8 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { /* Size: long long */ if (_p[0] == 'l' && _p[1] == 'l') { _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,long long); + if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { + va_arg(ap, long long); goto fmt_valid; } goto fmt_invalid; @@ -448,8 +462,8 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { /* Size: long */ if (_p[0] == 'l') { _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,long); + if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { + va_arg(ap, long); goto fmt_valid; } goto fmt_invalid; @@ -460,15 +474,15 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { goto format_err; fmt_valid: - _l = (_p+1)-c; - if (_l < sizeof(_format)-2) { - memcpy(_format,c,_l); + _l = (_p + 1) - c; + if (_l < sizeof(_format) - 2) { + memcpy(_format, c, _l); _format[_l] = '\0'; - newarg = sdscatvprintf(curarg,_format,_cpy); + newarg = sdscatvprintf(curarg, _format, _cpy); /* Update current position (note: outer blocks * increment c twice so compensate here) */ - c = _p-1; + c = _p - 1; } va_end(_cpy); @@ -476,7 +490,8 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { } } - if (newarg == NULL) goto memory_err; + if (newarg == NULL) + goto memory_err; curarg = newarg; touched = 1; @@ -489,8 +504,9 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { /* Add the last argument if needed */ if (touched) { - newargv = vk_realloc(curargv,sizeof(char*)*(argc+1)); - if (newargv == NULL) goto memory_err; + newargv = vk_realloc(curargv, sizeof(char *) * (argc + 1)); + if (newargv == NULL) + goto memory_err; curargv = newargv; curargv[argc++] = curarg; totlen += bulklen(sdslen(curarg)); @@ -502,16 +518,17 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { curarg = NULL; /* Add bytes needed to hold multi bulk count */ - totlen += 1+countDigits(argc)+2; + totlen += 1 + countDigits(argc) + 2; /* Build the command at protocol level */ - cmd = vk_malloc(totlen+1); - if (cmd == NULL) goto memory_err; + cmd = vk_malloc(totlen + 1); + if (cmd == NULL) + goto memory_err; - pos = sprintf(cmd,"*%d\r\n",argc); + pos = sprintf(cmd, "*%d\r\n", argc); for (j = 0; j < argc; j++) { - pos += sprintf(cmd+pos,"$%zu\r\n",sdslen(curargv[j])); - memcpy(cmd+pos,curargv[j],sdslen(curargv[j])); + pos += sprintf(cmd + pos, "$%zu\r\n", sdslen(curargv[j])); + memcpy(cmd + pos, curargv[j], sdslen(curargv[j])); pos += sdslen(curargv[j]); sdsfree(curargv[j]); cmd[pos++] = '\r'; @@ -534,7 +551,7 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { cleanup: if (curargv) { - while(argc--) + while (argc--) sdsfree(curargv[argc]); vk_free(curargv); } @@ -560,8 +577,8 @@ int valkeyvFormatCommand(char **target, const char *format, va_list ap) { int valkeyFormatCommand(char **target, const char *format, ...) { va_list ap; int len; - va_start(ap,format); - len = valkeyvFormatCommand(target,format,ap); + va_start(ap, format); + len = valkeyvFormatCommand(target, format, ap); va_end(ap); /* The API says "-1" means bad result, but we now also return "-2" in some @@ -579,8 +596,7 @@ int valkeyFormatCommand(char **target, const char *format, ...) { * argument lengths. */ long long valkeyFormatSdsCommandArgv(sds *target, int argc, const char **argv, - const size_t *argvlen) -{ + const size_t *argvlen) { sds cmd, aux; unsigned long long totlen, len; int j; @@ -590,7 +606,7 @@ long long valkeyFormatSdsCommandArgv(sds *target, int argc, const char **argv, return -1; /* Calculate our total size */ - totlen = 1+countDigits(argc)+2; + totlen = 1 + countDigits(argc) + 2; for (j = 0; j < argc; j++) { len = argvlen ? argvlen[j] : strlen(argv[j]); totlen += bulklen(len); @@ -612,14 +628,14 @@ long long valkeyFormatSdsCommandArgv(sds *target, int argc, const char **argv, /* Construct command */ cmd = sdscatfmt(cmd, "*%i\r\n", argc); - for (j=0; j < argc; j++) { + for (j = 0; j < argc; j++) { len = argvlen ? argvlen[j] : strlen(argv[j]); cmd = sdscatfmt(cmd, "$%U\r\n", len); cmd = sdscatlen(cmd, argv[j], len); - cmd = sdscatlen(cmd, "\r\n", sizeof("\r\n")-1); + cmd = sdscatlen(cmd, "\r\n", sizeof("\r\n") - 1); } - assert(sdslen(cmd)==totlen); + assert(sdslen(cmd) == totlen); *target = cmd; return totlen; @@ -636,7 +652,7 @@ void valkeyFreeSdsCommand(sds cmd) { */ long long valkeyFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen) { char *cmd = NULL; /* final command */ - size_t pos; /* position in final command */ + size_t pos; /* position in final command */ size_t len, totlen; int j; @@ -645,22 +661,22 @@ long long valkeyFormatCommandArgv(char **target, int argc, const char **argv, co return -1; /* Calculate number of bytes needed for the command */ - totlen = 1+countDigits(argc)+2; + totlen = 1 + countDigits(argc) + 2; for (j = 0; j < argc; j++) { len = argvlen ? argvlen[j] : strlen(argv[j]); totlen += bulklen(len); } /* Build the command at protocol level */ - cmd = vk_malloc(totlen+1); + cmd = vk_malloc(totlen + 1); if (cmd == NULL) return -1; - pos = sprintf(cmd,"*%d\r\n",argc); + pos = sprintf(cmd, "*%d\r\n", argc); for (j = 0; j < argc; j++) { len = argvlen ? argvlen[j] : strlen(argv[j]); - pos += sprintf(cmd+pos,"$%zu\r\n",len); - memcpy(cmd+pos,argv[j],len); + pos += sprintf(cmd + pos, "$%zu\r\n", len); + memcpy(cmd + pos, argv[j], len); pos += len; cmd[pos++] = '\r'; cmd[pos++] = '\n'; @@ -682,8 +698,8 @@ void valkeySetError(valkeyContext *c, int type, const char *str) { c->err = type; if (str != NULL) { len = strlen(str); - len = len < (sizeof(c->errstr)-1) ? len : (sizeof(c->errstr)-1); - memcpy(c->errstr,str,len); + len = len < (sizeof(c->errstr) - 1) ? len : (sizeof(c->errstr) - 1); + memcpy(c->errstr, str, len); c->errstr[len] = '\0'; } else { /* Only VALKEY_ERR_IO may lack a description! */ @@ -755,7 +771,7 @@ valkeyFD valkeyFreeKeepFd(valkeyContext *c) { } int valkeyReconnect(valkeyContext *c) { - valkeyOptions options = { .connect_timeout = c->connect_timeout }; + valkeyOptions options = {.connect_timeout = c->connect_timeout}; c->err = 0; memset(c->errstr, '\0', strlen(c->errstr)); @@ -794,7 +810,7 @@ int valkeyReconnect(valkeyContext *c) { default: /* Something bad happened here and shouldn't have. There isn't enough information in the context to reconnect. */ - valkeySetError(c,VALKEY_ERR_OTHER,"Not enough information to reconnect"); + valkeySetError(c, VALKEY_ERR_OTHER, "Not enough information to reconnect"); return VALKEY_ERR; } @@ -859,8 +875,7 @@ valkeyContext *valkeyConnectWithOptions(const valkeyOptions *options) { valkeyContextSetFuncs(c); c->funcs->connect(c, options); if (c->err == 0 && c->fd != VALKEY_INVALID_FD && - options->command_timeout != NULL && (c->flags & VALKEY_BLOCK)) - { + options->command_timeout != NULL && (c->flags & VALKEY_BLOCK)) { c->funcs->set_timeout(c, *options->command_timeout); } @@ -891,7 +906,7 @@ valkeyContext *valkeyConnectNonBlock(const char *ip, int port) { } valkeyContext *valkeyConnectBindNonBlock(const char *ip, int port, - const char *source_addr) { + const char *source_addr) { valkeyOptions options = {0}; VALKEY_OPTIONS_SET_TCP(&options, ip, port); options.endpoint.tcp.source_addr = source_addr; @@ -900,11 +915,11 @@ valkeyContext *valkeyConnectBindNonBlock(const char *ip, int port, } valkeyContext *valkeyConnectBindNonBlockWithReuse(const char *ip, int port, - const char *source_addr) { + const char *source_addr) { valkeyOptions options = {0}; VALKEY_OPTIONS_SET_TCP(&options, ip, port); options.endpoint.tcp.source_addr = source_addr; - options.options |= VALKEY_OPT_NONBLOCK|VALKEY_OPT_REUSEADDR; + options.options |= VALKEY_OPT_NONBLOCK | VALKEY_OPT_REUSEADDR; return valkeyConnectWithOptions(&options); } @@ -945,7 +960,7 @@ int valkeySetTimeout(valkeyContext *c, const struct timeval tv) { return VALKEY_ERR; } - return c->funcs->set_timeout(c,tv); + return c->funcs->set_timeout(c, tv); } int valkeyEnableKeepAliveWithInterval(valkeyContext *c, int interval) { @@ -975,7 +990,7 @@ valkeyPushFn *valkeySetPushCallback(valkeyContext *c, valkeyPushFn *fn) { * After this function is called, you may use valkeyGetReplyFromReader to * see if there is a reply available. */ int valkeyBufferRead(valkeyContext *c) { - char buf[1024*16]; + char buf[1024 * 16]; int nread; /* Return early when the context has seen an error. */ @@ -1019,11 +1034,13 @@ int valkeyBufferWrite(valkeyContext *c, int *done) { if (c->obuf == NULL) goto oom; } else { - if (sdsrange(c->obuf,nwritten,-1) < 0) goto oom; + if (sdsrange(c->obuf, nwritten, -1) < 0) + goto oom; } } } - if (done != NULL) *done = (sdslen(c->obuf) == 0); + if (done != NULL) + *done = (sdslen(c->obuf) == 0); return VALKEY_OK; oom: @@ -1045,7 +1062,7 @@ static int valkeyHandledPushReply(valkeyContext *c, void *reply) { /* Get a reply from our reader or set an error in the context. */ int valkeyGetReplyFromReader(valkeyContext *c, void **reply) { if (valkeyReaderGetReply(c->reader, reply) == VALKEY_ERR) { - valkeySetError(c,c->reader->err,c->reader->errstr); + valkeySetError(c, c->reader->err, c->reader->errstr); return VALKEY_ERR; } @@ -1069,14 +1086,14 @@ int valkeyGetReply(valkeyContext *c, void **reply) { void *aux = NULL; /* Try to read pending replies */ - if (valkeyNextInBandReplyFromReader(c,&aux) == VALKEY_ERR) + if (valkeyNextInBandReplyFromReader(c, &aux) == VALKEY_ERR) return VALKEY_ERR; /* For the blocking context, flush output buffer and read reply */ if (aux == NULL && c->flags & VALKEY_BLOCK) { /* Write until done */ do { - if (valkeyBufferWrite(c,&wdone) == VALKEY_ERR) + if (valkeyBufferWrite(c, &wdone) == VALKEY_ERR) return VALKEY_ERR; } while (!wdone); @@ -1085,7 +1102,7 @@ int valkeyGetReply(valkeyContext *c, void **reply) { if (valkeyBufferRead(c) == VALKEY_ERR) return VALKEY_ERR; - if (valkeyNextInBandReplyFromReader(c,&aux) == VALKEY_ERR) + if (valkeyNextInBandReplyFromReader(c, &aux) == VALKEY_ERR) return VALKEY_ERR; } while (aux == NULL); } @@ -1100,7 +1117,6 @@ int valkeyGetReply(valkeyContext *c, void **reply) { return VALKEY_OK; } - /* Helper function for the valkeyAppendCommand* family of functions. * * Write a formatted command to the output buffer. When this family @@ -1110,9 +1126,9 @@ int valkeyGetReply(valkeyContext *c, void **reply) { int valkeyAppendCmdLen(valkeyContext *c, const char *cmd, size_t len) { sds newbuf; - newbuf = sdscatlen(c->obuf,cmd,len); + newbuf = sdscatlen(c->obuf, cmd, len); if (newbuf == NULL) { - valkeySetError(c,VALKEY_ERR_OOM,"Out of memory"); + valkeySetError(c, VALKEY_ERR_OOM, "Out of memory"); return VALKEY_ERR; } @@ -1133,16 +1149,16 @@ int valkeyvAppendCommand(valkeyContext *c, const char *format, va_list ap) { char *cmd; int len; - len = valkeyvFormatCommand(&cmd,format,ap); + len = valkeyvFormatCommand(&cmd, format, ap); if (len == -1) { - valkeySetError(c,VALKEY_ERR_OOM,"Out of memory"); + valkeySetError(c, VALKEY_ERR_OOM, "Out of memory"); return VALKEY_ERR; } else if (len == -2) { - valkeySetError(c,VALKEY_ERR_OTHER,"Invalid format string"); + valkeySetError(c, VALKEY_ERR_OTHER, "Invalid format string"); return VALKEY_ERR; } - if (valkeyAppendCmdLen(c,cmd,len) != VALKEY_OK) { + if (valkeyAppendCmdLen(c, cmd, len) != VALKEY_OK) { vk_free(cmd); return VALKEY_ERR; } @@ -1155,8 +1171,8 @@ int valkeyAppendCommand(valkeyContext *c, const char *format, ...) { va_list ap; int ret; - va_start(ap,format); - ret = valkeyvAppendCommand(c,format,ap); + va_start(ap, format); + ret = valkeyvAppendCommand(c, format, ap); va_end(ap); return ret; } @@ -1165,13 +1181,13 @@ int valkeyAppendCommandArgv(valkeyContext *c, int argc, const char **argv, const sds cmd; long long len; - len = valkeyFormatSdsCommandArgv(&cmd,argc,argv,argvlen); + len = valkeyFormatSdsCommandArgv(&cmd, argc, argv, argvlen); if (len == -1) { - valkeySetError(c,VALKEY_ERR_OOM,"Out of memory"); + valkeySetError(c, VALKEY_ERR_OOM, "Out of memory"); return VALKEY_ERR; } - if (valkeyAppendCmdLen(c,cmd,len) != VALKEY_OK) { + if (valkeyAppendCmdLen(c, cmd, len) != VALKEY_OK) { sdsfree(cmd); return VALKEY_ERR; } @@ -1195,7 +1211,7 @@ static void *valkeyBlockForReply(valkeyContext *c) { void *reply; if (c->flags & VALKEY_BLOCK) { - if (valkeyGetReply(c,&reply) != VALKEY_OK) + if (valkeyGetReply(c, &reply) != VALKEY_OK) return NULL; return reply; } @@ -1203,21 +1219,21 @@ static void *valkeyBlockForReply(valkeyContext *c) { } void *valkeyvCommand(valkeyContext *c, const char *format, va_list ap) { - if (valkeyvAppendCommand(c,format,ap) != VALKEY_OK) + if (valkeyvAppendCommand(c, format, ap) != VALKEY_OK) return NULL; return valkeyBlockForReply(c); } void *valkeyCommand(valkeyContext *c, const char *format, ...) { va_list ap; - va_start(ap,format); - void *reply = valkeyvCommand(c,format,ap); + va_start(ap, format); + void *reply = valkeyvCommand(c, format, ap); va_end(ap); return reply; } void *valkeyCommandArgv(valkeyContext *c, int argc, const char **argv, const size_t *argvlen) { - if (valkeyAppendCommandArgv(c,argc,argv,argvlen) != VALKEY_OK) + if (valkeyAppendCommandArgv(c, argc, argv, argvlen) != VALKEY_OK) return NULL; return valkeyBlockForReply(c); } diff --git a/src/valkey_private.h b/src/valkey_private.h index cd493d83..ae48f8d7 100644 --- a/src/valkey_private.h +++ b/src/valkey_private.h @@ -31,19 +31,18 @@ #ifndef VALKEY_VK_PRIVATE_H #define VALKEY_VK_PRIVATE_H -#include "valkey.h" #include "win32.h" +#include "valkey.h" + #include #include - void valkeySetError(valkeyContext *c, int type, const char *str); - /* Helper function. Convert struct timeval to millisecond. */ static inline int valkeyContextTimeoutMsec(const struct timeval *timeout, long *result) { - long max_msec = ((LONG_MAX) - 999) / 1000; + long max_msec = (LONG_MAX - 999) / 1000; long msec = INT_MAX; /* Only use timeout when not NULL. */ @@ -129,4 +128,4 @@ void valkeyContextRegisterUserfdFuncs(void); void valkeyContextSetFuncs(valkeyContext *c); -#endif /* VALKEY_VK_PRIVATE_H */ +#endif /* VALKEY_VK_PRIVATE_H */ diff --git a/src/valkeycluster.c b/src/valkeycluster.c index c809ed03..c0f3023a 100644 --- a/src/valkeycluster.c +++ b/src/valkeycluster.c @@ -31,6 +31,16 @@ * POSSIBILITY OF SUCH DAMAGE. */ #define _XOPEN_SOURCE 600 +#include "win32.h" + +#include "valkeycluster.h" + +#include "adlist.h" +#include "alloc.h" +#include "command.h" +#include "dict.h" +#include "vkutil.h" + #include #include #include @@ -38,14 +48,6 @@ #include #include -#include "alloc.h" -#include "adlist.h" -#include "command.h" -#include "dict.h" -#include "valkeycluster.h" -#include "vkutil.h" -#include "win32.h" - // Cluster errors are offset by 100 to be sufficiently out of range of // standard Valkey errors #define VALKEY_ERR_CLUSTER_TOO_MANY_RETRIES 100 @@ -3122,8 +3124,8 @@ void clusterNodesReplyCallback(valkeyAsyncContext *ac, void *r, } } -#define nodeIsConnected(n) \ - ((n)->acon != NULL && (n)->acon->err == 0 && \ +#define nodeIsConnected(n) \ + ((n)->acon != NULL && (n)->acon->err == 0 && \ (n)->acon->c.flags & VALKEY_CONNECTED) /* Select a node. diff --git a/src/vkutil.c b/src/vkutil.c index 95bc9468..2752b8a9 100644 --- a/src/vkutil.c +++ b/src/vkutil.c @@ -35,9 +35,10 @@ #include #endif +#include "win32.h" + #include "alloc.h" #include "vkutil.h" -#include "win32.h" int _vk_atoi(uint8_t *line, size_t n) { int value; diff --git a/src/win32.h b/src/win32.h index bd649334..e693195b 100644 --- a/src/win32.h +++ b/src/win32.h @@ -51,14 +51,13 @@ #endif #ifndef va_copy -#define va_copy(d,s) ((d) = (s)) +#define va_copy(d, s) ((d) = (s)) #endif -#ifndef snprintf +#if !defined(snprintf) && _MSC_VER < 1900 #define snprintf c99_snprintf -__inline int c99_vsnprintf(char* str, size_t size, const char* format, va_list ap) -{ +__inline int c99_vsnprintf(char *str, size_t size, const char *format, va_list ap) { int count = -1; if (size != 0) @@ -69,8 +68,7 @@ __inline int c99_vsnprintf(char* str, size_t size, const char* format, va_list a return count; } -__inline int c99_snprintf(char* str, size_t size, const char* format, ...) -{ +__inline int c99_snprintf(char *str, size_t size, const char *format, ...) { int count; va_list ap; diff --git a/tests/client_test.c b/tests/client_test.c index 822dd1e2..7971f485 100644 --- a/tests/client_test.c +++ b/tests/client_test.c @@ -2,26 +2,27 @@ #define _POSIX_C_SOURCE 200112L #endif #include "sockcompat.h" + #include #include #include #ifndef _WIN32 #include -#include #include +#include #include #else #define strcasecmp _stricmp #endif +#include "adapters/poll.h" +#include "async.h" +#include "valkey.h" + #include -#include #include #include #include - -#include "valkey.h" -#include "async.h" -#include "adapters/poll.h" +#include #ifdef VALKEY_TEST_SSL #include "valkey_ssl.h" #endif @@ -30,6 +31,7 @@ #endif #ifdef VALKEY_TEST_ASYNC #include "adapters/libevent.h" + #include #endif @@ -85,15 +87,29 @@ valkeySSLContext *_ssl_ctx = NULL; /* The following lines make up our testing "framework" :) */ static int tests = 0, fails = 0, skips = 0; -#define test(_s) { printf("#%02d ", ++tests); printf(_s); } -#define test_cond(_c) if(_c) printf("\033[0;32mPASSED\033[0;0m\n"); else {printf("\033[0;31mFAILED\033[0;0m\n"); fails++;} -#define test_skipped() { printf("\033[01;33mSKIPPED\033[0;0m\n"); skips++; } +#define test(_s) \ + { \ + printf("#%02d ", ++tests); \ + printf(_s); \ + } +#define test_cond(_c) \ + if (_c) \ + printf("\033[0;32mPASSED\033[0;0m\n"); \ + else { \ + printf("\033[0;31mFAILED\033[0;0m\n"); \ + fails++; \ + } +#define test_skipped() \ + { \ + printf("\033[01;33mSKIPPED\033[0;0m\n"); \ + skips++; \ + } static void millisleep(int ms) { #ifdef _MSC_VER Sleep(ms); #else - struct timespec ts = { ms / 1000, (ms % 1000) * 1000000 }; + struct timespec ts = {ms / 1000, (ms % 1000) * 1000000}; nanosleep(&ts, NULL); #endif @@ -102,8 +118,8 @@ static void millisleep(int ms) { static long long usec(void) { #ifndef _MSC_VER struct timeval tv; - gettimeofday(&tv,NULL); - return (((long long)tv.tv_sec)*1000000)+tv.tv_usec; + gettimeofday(&tv, NULL); + return (((long long)tv.tv_sec) * 1000000) + tv.tv_usec; #else FILETIME ft; GetSystemTimeAsFileTime(&ft); @@ -118,11 +134,11 @@ static long long usec(void) { #define assert(e) (void)(e) #endif -#define valkeyTestPanic(msg) \ - do { \ +#define valkeyTestPanic(msg) \ + do { \ fprintf(stderr, "PANIC: %s (In function \"%s\", file \"%s\", line %d)\n", \ - msg, __func__, __FILE__, __LINE__); \ - exit(1); \ + msg, __func__, __FILE__, __LINE__); \ + exit(1); \ } while (1) /* Helper to extract server version information. Aborts on any failure. */ @@ -146,12 +162,15 @@ void get_server_version(valkeyContext *c, int *majorptr, int *minorptr) { /* Extract version info */ major = strtol(s, &eptr, 10); - if (*eptr != '.') goto abort; - minor = strtol(eptr+1, NULL, 10); + if (*eptr != '.') + goto abort; + minor = strtol(eptr + 1, NULL, 10); /* Push info the caller wants */ - if (majorptr) *majorptr = major; - if (minorptr) *minorptr = minor; + if (majorptr) + *majorptr = major; + if (minorptr) + *minorptr = minor; freeReplyObject(reply); return; @@ -166,12 +185,12 @@ static valkeyContext *select_database(valkeyContext *c) { valkeyReply *reply; /* Switch to DB 9 for testing, now that we know we can chat. */ - reply = valkeyCommand(c,"SELECT 9"); + reply = valkeyCommand(c, "SELECT 9"); assert(reply != NULL); freeReplyObject(reply); /* Make sure the DB is empty */ - reply = valkeyCommand(c,"DBSIZE"); + reply = valkeyCommand(c, "DBSIZE"); assert(reply != NULL); if (reply->type == VALKEY_REPLY_INTEGER && reply->integer == 0) { /* Awesome, DB 9 is empty and we can continue. */ @@ -208,10 +227,10 @@ static int disconnect(valkeyContext *c, int keep_fd) { valkeyReply *reply; /* Make sure we're on DB 9. */ - reply = valkeyCommand(c,"SELECT 9"); + reply = valkeyCommand(c, "SELECT 9"); assert(reply != NULL); freeReplyObject(reply); - reply = valkeyCommand(c,"FLUSHDB"); + reply = valkeyCommand(c, "FLUSHDB"); assert(reply != NULL); freeReplyObject(reply); @@ -231,7 +250,7 @@ static void do_ssl_handshake(valkeyContext *c) { exit(1); } #else - (void) c; + (void)c; #endif } @@ -291,67 +310,69 @@ static void test_format_commands(void) { int len; test("Format command without interpolation: "); - len = valkeyFormatCommand(&cmd,"SET foo bar"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); + len = valkeyFormatCommand(&cmd, "SET foo bar"); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (3 + 2)); vk_free(cmd); test("Format command with %%s string interpolation: "); - len = valkeyFormatCommand(&cmd,"SET %s %s","foo","bar"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); + len = valkeyFormatCommand(&cmd, "SET %s %s", "foo", "bar"); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (3 + 2)); vk_free(cmd); test("Format command with %%s and an empty string: "); - len = valkeyFormatCommand(&cmd,"SET %s %s","foo",""); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(0+2)); + len = valkeyFormatCommand(&cmd, "SET %s %s", "foo", ""); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (0 + 2)); vk_free(cmd); test("Format command with an empty string in between proper interpolations: "); - len = valkeyFormatCommand(&cmd,"SET %s %s","","foo"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$0\r\n\r\n$3\r\nfoo\r\n",len) == 0 && - len == 4+4+(3+2)+4+(0+2)+4+(3+2)); + len = valkeyFormatCommand(&cmd, "SET %s %s", "", "foo"); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$0\r\n\r\n$3\r\nfoo\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (0 + 2) + 4 + (3 + 2)); vk_free(cmd); test("Format command with %%b string interpolation: "); - len = valkeyFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"b\0r",(size_t)3); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nb\0r\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); + len = valkeyFormatCommand(&cmd, "SET %b %b", "foo", (size_t)3, "b\0r", (size_t)3); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nb\0r\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (3 + 2)); vk_free(cmd); test("Format command with %%b and an empty string: "); - len = valkeyFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"",(size_t)0); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(0+2)); + len = valkeyFormatCommand(&cmd, "SET %b %b", "foo", (size_t)3, "", (size_t)0); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (0 + 2)); vk_free(cmd); test("Format command with literal %%: "); - len = valkeyFormatCommand(&cmd,"SET %% %%"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$1\r\n%\r\n$1\r\n%\r\n",len) == 0 && - len == 4+4+(3+2)+4+(1+2)+4+(1+2)); + len = valkeyFormatCommand(&cmd, "SET %% %%"); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$1\r\n%\r\n$1\r\n%\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (1 + 2) + 4 + (1 + 2)); vk_free(cmd); /* Vararg width depends on the type. These tests make sure that the * width is correctly determined using the format and subsequent varargs * can correctly be interpolated. */ -#define INTEGER_WIDTH_TEST(fmt, type) do { \ - type value = 123; \ - test("Format command with printf-delegation (" #type "): "); \ - len = valkeyFormatCommand(&cmd,"key:%08" fmt " str:%s", value, "hello"); \ - test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:00000123\r\n$9\r\nstr:hello\r\n",len) == 0 && \ - len == 4+5+(12+2)+4+(9+2)); \ - vk_free(cmd); \ -} while(0) - -#define FLOAT_WIDTH_TEST(type) do { \ - type value = 123.0; \ - test("Format command with printf-delegation (" #type "): "); \ - len = valkeyFormatCommand(&cmd,"key:%08.3f str:%s", value, "hello"); \ - test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:0123.000\r\n$9\r\nstr:hello\r\n",len) == 0 && \ - len == 4+5+(12+2)+4+(9+2)); \ - vk_free(cmd); \ -} while(0) +#define INTEGER_WIDTH_TEST(fmt, type) \ + do { \ + type value = 123; \ + test("Format command with printf-delegation (" #type "): "); \ + len = valkeyFormatCommand(&cmd, "key:%08" fmt " str:%s", value, "hello"); \ + test_cond(strncmp(cmd, "*2\r\n$12\r\nkey:00000123\r\n$9\r\nstr:hello\r\n", len) == 0 && \ + len == 4 + 5 + (12 + 2) + 4 + (9 + 2)); \ + vk_free(cmd); \ + } while (0) + +#define FLOAT_WIDTH_TEST(type) \ + do { \ + type value = 123.0; \ + test("Format command with printf-delegation (" #type "): "); \ + len = valkeyFormatCommand(&cmd, "key:%08.3f str:%s", value, "hello"); \ + test_cond(strncmp(cmd, "*2\r\n$12\r\nkey:0123.000\r\n$9\r\nstr:hello\r\n", len) == 0 && \ + len == 4 + 5 + (12 + 2) + 4 + (9 + 2)); \ + vk_free(cmd); \ + } while (0) INTEGER_WIDTH_TEST("d", int); INTEGER_WIDTH_TEST("hhd", char); @@ -367,46 +388,46 @@ static void test_format_commands(void) { FLOAT_WIDTH_TEST(double); test("Format command with unhandled printf format (specifier 'p' not supported): "); - len = valkeyFormatCommand(&cmd,"key:%08p %b",(void*)1234,"foo",(size_t)3); + len = valkeyFormatCommand(&cmd, "key:%08p %b", (void *)1234, "foo", (size_t)3); test_cond(len == -1); test("Format command with invalid printf format (specifier missing): "); - len = valkeyFormatCommand(&cmd,"%-"); + len = valkeyFormatCommand(&cmd, "%-"); test_cond(len == -1); const char *argv[3]; argv[0] = "SET"; argv[1] = "foo\0xxx"; argv[2] = "bar"; - size_t lens[3] = { 3, 7, 3 }; + size_t lens[3] = {3, 7, 3}; int argc = 3; test("Format command by passing argc/argv without lengths: "); - len = valkeyFormatCommandArgv(&cmd,argc,argv,NULL); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); + len = valkeyFormatCommandArgv(&cmd, argc, argv, NULL); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (3 + 2)); vk_free(cmd); test("Format command by passing argc/argv with lengths: "); - len = valkeyFormatCommandArgv(&cmd,argc,argv,lens); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(7+2)+4+(3+2)); + len = valkeyFormatCommandArgv(&cmd, argc, argv, lens); + test_cond(strncmp(cmd, "*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (7 + 2) + 4 + (3 + 2)); vk_free(cmd); sds sds_cmd; sds_cmd = NULL; test("Format command into sds by passing argc/argv without lengths: "); - len = valkeyFormatSdsCommandArgv(&sds_cmd,argc,argv,NULL); - test_cond(strncmp(sds_cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); + len = valkeyFormatSdsCommandArgv(&sds_cmd, argc, argv, NULL); + test_cond(strncmp(sds_cmd, "*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (3 + 2) + 4 + (3 + 2)); sdsfree(sds_cmd); sds_cmd = NULL; test("Format command into sds by passing argc/argv with lengths: "); - len = valkeyFormatSdsCommandArgv(&sds_cmd,argc,argv,lens); - test_cond(strncmp(sds_cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(7+2)+4+(3+2)); + len = valkeyFormatSdsCommandArgv(&sds_cmd, argc, argv, lens); + test_cond(strncmp(sds_cmd, "*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n", len) == 0 && + len == 4 + 4 + (3 + 2) + 4 + (7 + 2) + 4 + (3 + 2)); sdsfree(sds_cmd); } @@ -424,7 +445,7 @@ static void test_append_formatted_commands(struct config config) { test_cond(valkeyAppendFormattedCommand(c, cmd, len) == VALKEY_OK); - assert(valkeyGetReply(c, (void*)&reply) == VALKEY_OK); + assert(valkeyGetReply(c, (void *)&reply) == VALKEY_OK); vk_free(cmd); freeReplyObject(reply); @@ -477,99 +498,99 @@ static void test_reply_reader(void) { test("Error handling in reply parser: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)"@foo\r\n",6); - ret = valkeyReaderGetReply(reader,NULL); + valkeyReaderFeed(reader, (char *)"@foo\r\n", 6); + ret = valkeyReaderGetReply(reader, NULL); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0); + strcasecmp(reader->errstr, "Protocol error, got \"@\" as reply type byte") == 0); valkeyReaderFree(reader); /* when the reply already contains multiple items, they must be free'd * on an error. valgrind will bark when this doesn't happen. */ test("Memory cleanup in reply parser: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)"*2\r\n",4); - valkeyReaderFeed(reader,(char*)"$5\r\nhello\r\n",11); - valkeyReaderFeed(reader,(char*)"@foo\r\n",6); - ret = valkeyReaderGetReply(reader,NULL); + valkeyReaderFeed(reader, (char *)"*2\r\n", 4); + valkeyReaderFeed(reader, (char *)"$5\r\nhello\r\n", 11); + valkeyReaderFeed(reader, (char *)"@foo\r\n", 6); + ret = valkeyReaderGetReply(reader, NULL); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0); + strcasecmp(reader->errstr, "Protocol error, got \"@\" as reply type byte") == 0); valkeyReaderFree(reader); reader = valkeyReaderCreate(); test("Can handle arbitrarily nested multi-bulks: "); for (i = 0; i < 128; i++) { - valkeyReaderFeed(reader,(char*)"*1\r\n", 4); + valkeyReaderFeed(reader, (char *)"*1\r\n", 4); } - valkeyReaderFeed(reader,(char*)"$6\r\nLOLWUT\r\n",12); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"$6\r\nLOLWUT\r\n", 12); + ret = valkeyReaderGetReply(reader, &reply); root = reply; /* Keep track of the root reply */ test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_ARRAY && - ((valkeyReply*)reply)->elements == 1); + ((valkeyReply *)reply)->type == VALKEY_REPLY_ARRAY && + ((valkeyReply *)reply)->elements == 1); test("Can parse arbitrarily nested multi-bulks correctly: "); - while(i--) { - assert(reply != NULL && ((valkeyReply*)reply)->type == VALKEY_REPLY_ARRAY); - reply = ((valkeyReply*)reply)->element[0]; + while (i--) { + assert(reply != NULL && ((valkeyReply *)reply)->type == VALKEY_REPLY_ARRAY); + reply = ((valkeyReply *)reply)->element[0]; } - test_cond(((valkeyReply*)reply)->type == VALKEY_REPLY_STRING && - !memcmp(((valkeyReply*)reply)->str, "LOLWUT", 6)); + test_cond(((valkeyReply *)reply)->type == VALKEY_REPLY_STRING && + !memcmp(((valkeyReply *)reply)->str, "LOLWUT", 6)); freeReplyObject(root); valkeyReaderFree(reader); test("Correctly parses LLONG_MAX: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ":9223372036854775807\r\n",22); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ":9223372036854775807\r\n", 22); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->integer == LLONG_MAX); + ((valkeyReply *)reply)->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->integer == LLONG_MAX); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error when > LLONG_MAX: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ":9223372036854775808\r\n",22); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ":9223372036854775808\r\n", 22); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bad integer value") == 0); + strcasecmp(reader->errstr, "Bad integer value") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Correctly parses LLONG_MIN: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ":-9223372036854775808\r\n",23); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ":-9223372036854775808\r\n", 23); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->integer == LLONG_MIN); + ((valkeyReply *)reply)->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->integer == LLONG_MIN); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error when < LLONG_MIN: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ":-9223372036854775809\r\n",23); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ":-9223372036854775809\r\n", 23); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bad integer value") == 0); + strcasecmp(reader->errstr, "Bad integer value") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error when array < -1: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "*-2\r\n+asdf\r\n",12); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "*-2\r\n+asdf\r\n", 12); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Multi-bulk length out of range") == 0); + strcasecmp(reader->errstr, "Multi-bulk length out of range") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error when bulk < -1: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "$-2\r\nasdf\r\n",11); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "$-2\r\nasdf\r\n", 11); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bulk string length out of range") == 0); + strcasecmp(reader->errstr, "Bulk string length out of range") == 0); freeReplyObject(reply); valkeyReaderFree(reader); @@ -577,7 +598,7 @@ static void test_reply_reader(void) { reader = valkeyReaderCreate(); reader->maxelements = 1024; valkeyReaderFeed(reader, "*1025\r\n", 7); - ret = valkeyReaderGetReply(reader,&reply); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && strcasecmp(reader->errstr, "Multi-bulk length out of range") == 0); freeReplyObject(reply); @@ -587,12 +608,12 @@ static void test_reply_reader(void) { size_t bad_mbulk_len = (SIZE_MAX / sizeof(void *)) + 3; char bad_mbulk_reply[100]; snprintf(bad_mbulk_reply, sizeof(bad_mbulk_reply), "*%llu\r\n+asdf\r\n", - (unsigned long long) bad_mbulk_len); + (unsigned long long)bad_mbulk_len); reader = valkeyReaderCreate(); - reader->maxelements = 0; /* Don't rely on default limit */ + reader->maxelements = 0; /* Don't rely on default limit */ valkeyReaderFeed(reader, bad_mbulk_reply, strlen(bad_mbulk_reply)); - ret = valkeyReaderGetReply(reader,&reply); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && strcasecmp(reader->errstr, "Out of memory") == 0); freeReplyObject(reply); valkeyReaderFree(reader); @@ -600,19 +621,19 @@ static void test_reply_reader(void) { #if LLONG_MAX > SIZE_MAX test("Set error when array > SIZE_MAX: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "*9223372036854775807\r\n+asdf\r\n",29); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "*9223372036854775807\r\n+asdf\r\n", 29); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Multi-bulk length out of range") == 0); + strcasecmp(reader->errstr, "Multi-bulk length out of range") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error when bulk > SIZE_MAX: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "$9223372036854775807\r\nasdf\r\n",28); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "$9223372036854775807\r\nasdf\r\n", 28); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bulk string length out of range") == 0); + strcasecmp(reader->errstr, "Bulk string length out of range") == 0); freeReplyObject(reply); valkeyReaderFree(reader); #endif @@ -620,121 +641,121 @@ static void test_reply_reader(void) { test("Works with NULL functions for reply: "); reader = valkeyReaderCreate(); reader->fn = NULL; - valkeyReaderFeed(reader,(char*)"+OK\r\n",5); - ret = valkeyReaderGetReply(reader,&reply); - test_cond(ret == VALKEY_OK && reply == (void*)VALKEY_REPLY_STATUS); + valkeyReaderFeed(reader, (char *)"+OK\r\n", 5); + ret = valkeyReaderGetReply(reader, &reply); + test_cond(ret == VALKEY_OK && reply == (void *)VALKEY_REPLY_STATUS); valkeyReaderFree(reader); test("Works when a single newline (\\r\\n) covers two calls to feed: "); reader = valkeyReaderCreate(); reader->fn = NULL; - valkeyReaderFeed(reader,(char*)"+OK\r",4); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"+OK\r", 4); + ret = valkeyReaderGetReply(reader, &reply); assert(ret == VALKEY_OK && reply == NULL); - valkeyReaderFeed(reader,(char*)"\n",1); - ret = valkeyReaderGetReply(reader,&reply); - test_cond(ret == VALKEY_OK && reply == (void*)VALKEY_REPLY_STATUS); + valkeyReaderFeed(reader, (char *)"\n", 1); + ret = valkeyReaderGetReply(reader, &reply); + test_cond(ret == VALKEY_OK && reply == (void *)VALKEY_REPLY_STATUS); valkeyReaderFree(reader); test("Don't reset state after protocol error: "); reader = valkeyReaderCreate(); reader->fn = NULL; - valkeyReaderFeed(reader,(char*)"x",1); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"x", 1); + ret = valkeyReaderGetReply(reader, &reply); assert(ret == VALKEY_ERR); - ret = valkeyReaderGetReply(reader,&reply); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && reply == NULL); valkeyReaderFree(reader); test("Don't reset state after protocol error(not segfault): "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)"*3\r\n$3\r\nSET\r\n$5\r\nhello\r\n$", 25); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"*3\r\n$3\r\nSET\r\n$5\r\nhello\r\n$", 25); + ret = valkeyReaderGetReply(reader, &reply); assert(ret == VALKEY_OK); - valkeyReaderFeed(reader,(char*)"3\r\nval\r\n", 8); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"3\r\nval\r\n", 8); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_ARRAY && - ((valkeyReply*)reply)->elements == 3); + ((valkeyReply *)reply)->type == VALKEY_REPLY_ARRAY && + ((valkeyReply *)reply)->elements == 3); freeReplyObject(reply); valkeyReaderFree(reader); /* Regression test for issue #45 on GitHub. */ test("Don't do empty allocation for empty multi bulk: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)"*0\r\n",4); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"*0\r\n", 4); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_ARRAY && - ((valkeyReply*)reply)->elements == 0); + ((valkeyReply *)reply)->type == VALKEY_REPLY_ARRAY && + ((valkeyReply *)reply)->elements == 0); freeReplyObject(reply); valkeyReaderFree(reader); /* RESP3 verbatim strings (GitHub issue #802) */ test("Can parse RESP3 verbatim strings: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)"=10\r\ntxt:LOLWUT\r\n",17); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)"=10\r\ntxt:LOLWUT\r\n", 17); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_VERB && - !memcmp(((valkeyReply*)reply)->str,"LOLWUT", 6)); + ((valkeyReply *)reply)->type == VALKEY_REPLY_VERB && + !memcmp(((valkeyReply *)reply)->str, "LOLWUT", 6)); freeReplyObject(reply); valkeyReaderFree(reader); /* RESP3 push messages (Github issue #815) */ test("Can parse RESP3 push messages: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,(char*)">2\r\n$6\r\nLOLWUT\r\n:42\r\n",21); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, (char *)">2\r\n$6\r\nLOLWUT\r\n:42\r\n", 21); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_PUSH && - ((valkeyReply*)reply)->elements == 2 && - ((valkeyReply*)reply)->element[0]->type == VALKEY_REPLY_STRING && - !memcmp(((valkeyReply*)reply)->element[0]->str,"LOLWUT",6) && - ((valkeyReply*)reply)->element[1]->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->element[1]->integer == 42); + ((valkeyReply *)reply)->type == VALKEY_REPLY_PUSH && + ((valkeyReply *)reply)->elements == 2 && + ((valkeyReply *)reply)->element[0]->type == VALKEY_REPLY_STRING && + !memcmp(((valkeyReply *)reply)->element[0]->str, "LOLWUT", 6) && + ((valkeyReply *)reply)->element[1]->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->element[1]->integer == 42); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 doubles: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ",3.14159265358979323846\r\n",25); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ",3.14159265358979323846\r\n", 25); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_DOUBLE && - fabs(((valkeyReply*)reply)->dval - 3.14159265358979323846) < 0.00000001 && - ((valkeyReply*)reply)->len == 22 && - strcmp(((valkeyReply*)reply)->str, "3.14159265358979323846") == 0); + ((valkeyReply *)reply)->type == VALKEY_REPLY_DOUBLE && + fabs(((valkeyReply *)reply)->dval - 3.14159265358979323846) < 0.00000001 && + ((valkeyReply *)reply)->len == 22 && + strcmp(((valkeyReply *)reply)->str, "3.14159265358979323846") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error on invalid RESP3 double: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ",3.14159\000265358979323846\r\n",26); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ",3.14159\000265358979323846\r\n", 26); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bad double value") == 0); + strcasecmp(reader->errstr, "Bad double value") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Correctly parses RESP3 double INFINITY: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ",inf\r\n",6); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ",inf\r\n", 6); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_DOUBLE && - isinf(((valkeyReply*)reply)->dval) && - ((valkeyReply*)reply)->dval > 0); + ((valkeyReply *)reply)->type == VALKEY_REPLY_DOUBLE && + isinf(((valkeyReply *)reply)->dval) && + ((valkeyReply *)reply)->dval > 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Correctly parses RESP3 double NaN: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, ",nan\r\n",6); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, ",nan\r\n", 6); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_DOUBLE && - isnan(((valkeyReply*)reply)->dval)); + ((valkeyReply *)reply)->type == VALKEY_REPLY_DOUBLE && + isnan(((valkeyReply *)reply)->dval)); freeReplyObject(reply); valkeyReaderFree(reader); @@ -743,142 +764,142 @@ static void test_reply_reader(void) { valkeyReaderFeed(reader, ",-nan\r\n", 7); ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_DOUBLE && - isnan(((valkeyReply*)reply)->dval)); + ((valkeyReply *)reply)->type == VALKEY_REPLY_DOUBLE && + isnan(((valkeyReply *)reply)->dval)); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 nil: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "_\r\n",3); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "_\r\n", 3); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_NIL); + ((valkeyReply *)reply)->type == VALKEY_REPLY_NIL); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error on invalid RESP3 nil: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "_nil\r\n",6); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "_nil\r\n", 6); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bad nil value") == 0); + strcasecmp(reader->errstr, "Bad nil value") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 bool (true): "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "#t\r\n",4); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "#t\r\n", 4); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_BOOL && - ((valkeyReply*)reply)->integer); + ((valkeyReply *)reply)->type == VALKEY_REPLY_BOOL && + ((valkeyReply *)reply)->integer); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 bool (false): "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "#f\r\n",4); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "#f\r\n", 4); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_BOOL && - !((valkeyReply*)reply)->integer); + ((valkeyReply *)reply)->type == VALKEY_REPLY_BOOL && + !((valkeyReply *)reply)->integer); freeReplyObject(reply); valkeyReaderFree(reader); test("Set error on invalid RESP3 bool: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "#foobar\r\n",9); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "#foobar\r\n", 9); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_ERR && - strcasecmp(reader->errstr,"Bad bool value") == 0); + strcasecmp(reader->errstr, "Bad bool value") == 0); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 map: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "%2\r\n+first\r\n:123\r\n$6\r\nsecond\r\n#t\r\n",34); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "%2\r\n+first\r\n:123\r\n$6\r\nsecond\r\n#t\r\n", 34); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_MAP && - ((valkeyReply*)reply)->elements == 4 && - ((valkeyReply*)reply)->element[0]->type == VALKEY_REPLY_STATUS && - ((valkeyReply*)reply)->element[0]->len == 5 && - !strcmp(((valkeyReply*)reply)->element[0]->str,"first") && - ((valkeyReply*)reply)->element[1]->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->element[1]->integer == 123 && - ((valkeyReply*)reply)->element[2]->type == VALKEY_REPLY_STRING && - ((valkeyReply*)reply)->element[2]->len == 6 && - !strcmp(((valkeyReply*)reply)->element[2]->str,"second") && - ((valkeyReply*)reply)->element[3]->type == VALKEY_REPLY_BOOL && - ((valkeyReply*)reply)->element[3]->integer); + ((valkeyReply *)reply)->type == VALKEY_REPLY_MAP && + ((valkeyReply *)reply)->elements == 4 && + ((valkeyReply *)reply)->element[0]->type == VALKEY_REPLY_STATUS && + ((valkeyReply *)reply)->element[0]->len == 5 && + !strcmp(((valkeyReply *)reply)->element[0]->str, "first") && + ((valkeyReply *)reply)->element[1]->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->element[1]->integer == 123 && + ((valkeyReply *)reply)->element[2]->type == VALKEY_REPLY_STRING && + ((valkeyReply *)reply)->element[2]->len == 6 && + !strcmp(((valkeyReply *)reply)->element[2]->str, "second") && + ((valkeyReply *)reply)->element[3]->type == VALKEY_REPLY_BOOL && + ((valkeyReply *)reply)->element[3]->integer); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 attribute: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "|2\r\n+foo\r\n:123\r\n+bar\r\n#t\r\n",26); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "|2\r\n+foo\r\n:123\r\n+bar\r\n#t\r\n", 26); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_ATTR && - ((valkeyReply*)reply)->elements == 4 && - ((valkeyReply*)reply)->element[0]->type == VALKEY_REPLY_STATUS && - ((valkeyReply*)reply)->element[0]->len == 3 && - !strcmp(((valkeyReply*)reply)->element[0]->str,"foo") && - ((valkeyReply*)reply)->element[1]->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->element[1]->integer == 123 && - ((valkeyReply*)reply)->element[2]->type == VALKEY_REPLY_STATUS && - ((valkeyReply*)reply)->element[2]->len == 3 && - !strcmp(((valkeyReply*)reply)->element[2]->str,"bar") && - ((valkeyReply*)reply)->element[3]->type == VALKEY_REPLY_BOOL && - ((valkeyReply*)reply)->element[3]->integer); + ((valkeyReply *)reply)->type == VALKEY_REPLY_ATTR && + ((valkeyReply *)reply)->elements == 4 && + ((valkeyReply *)reply)->element[0]->type == VALKEY_REPLY_STATUS && + ((valkeyReply *)reply)->element[0]->len == 3 && + !strcmp(((valkeyReply *)reply)->element[0]->str, "foo") && + ((valkeyReply *)reply)->element[1]->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->element[1]->integer == 123 && + ((valkeyReply *)reply)->element[2]->type == VALKEY_REPLY_STATUS && + ((valkeyReply *)reply)->element[2]->len == 3 && + !strcmp(((valkeyReply *)reply)->element[2]->str, "bar") && + ((valkeyReply *)reply)->element[3]->type == VALKEY_REPLY_BOOL && + ((valkeyReply *)reply)->element[3]->integer); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 set: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "~5\r\n+orange\r\n$5\r\napple\r\n#f\r\n:100\r\n:999\r\n",40); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "~5\r\n+orange\r\n$5\r\napple\r\n#f\r\n:100\r\n:999\r\n", 40); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_SET && - ((valkeyReply*)reply)->elements == 5 && - ((valkeyReply*)reply)->element[0]->type == VALKEY_REPLY_STATUS && - ((valkeyReply*)reply)->element[0]->len == 6 && - !strcmp(((valkeyReply*)reply)->element[0]->str,"orange") && - ((valkeyReply*)reply)->element[1]->type == VALKEY_REPLY_STRING && - ((valkeyReply*)reply)->element[1]->len == 5 && - !strcmp(((valkeyReply*)reply)->element[1]->str,"apple") && - ((valkeyReply*)reply)->element[2]->type == VALKEY_REPLY_BOOL && - !((valkeyReply*)reply)->element[2]->integer && - ((valkeyReply*)reply)->element[3]->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->element[3]->integer == 100 && - ((valkeyReply*)reply)->element[4]->type == VALKEY_REPLY_INTEGER && - ((valkeyReply*)reply)->element[4]->integer == 999); + ((valkeyReply *)reply)->type == VALKEY_REPLY_SET && + ((valkeyReply *)reply)->elements == 5 && + ((valkeyReply *)reply)->element[0]->type == VALKEY_REPLY_STATUS && + ((valkeyReply *)reply)->element[0]->len == 6 && + !strcmp(((valkeyReply *)reply)->element[0]->str, "orange") && + ((valkeyReply *)reply)->element[1]->type == VALKEY_REPLY_STRING && + ((valkeyReply *)reply)->element[1]->len == 5 && + !strcmp(((valkeyReply *)reply)->element[1]->str, "apple") && + ((valkeyReply *)reply)->element[2]->type == VALKEY_REPLY_BOOL && + !((valkeyReply *)reply)->element[2]->integer && + ((valkeyReply *)reply)->element[3]->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->element[3]->integer == 100 && + ((valkeyReply *)reply)->element[4]->type == VALKEY_REPLY_INTEGER && + ((valkeyReply *)reply)->element[4]->integer == 999); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 bignum: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader,"(3492890328409238509324850943850943825024385\r\n",46); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "(3492890328409238509324850943850943825024385\r\n", 46); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_BIGNUM && - ((valkeyReply*)reply)->len == 43 && - !strcmp(((valkeyReply*)reply)->str,"3492890328409238509324850943850943825024385")); + ((valkeyReply *)reply)->type == VALKEY_REPLY_BIGNUM && + ((valkeyReply *)reply)->len == 43 && + !strcmp(((valkeyReply *)reply)->str, "3492890328409238509324850943850943825024385")); freeReplyObject(reply); valkeyReaderFree(reader); test("Can parse RESP3 doubles in an array: "); reader = valkeyReaderCreate(); - valkeyReaderFeed(reader, "*1\r\n,3.14159265358979323846\r\n",31); - ret = valkeyReaderGetReply(reader,&reply); + valkeyReaderFeed(reader, "*1\r\n,3.14159265358979323846\r\n", 31); + ret = valkeyReaderGetReply(reader, &reply); test_cond(ret == VALKEY_OK && - ((valkeyReply*)reply)->type == VALKEY_REPLY_ARRAY && - ((valkeyReply*)reply)->elements == 1 && - ((valkeyReply*)reply)->element[0]->type == VALKEY_REPLY_DOUBLE && - fabs(((valkeyReply*)reply)->element[0]->dval - 3.14159265358979323846) < 0.00000001 && - ((valkeyReply*)reply)->element[0]->len == 22 && - strcmp(((valkeyReply*)reply)->element[0]->str, "3.14159265358979323846") == 0); + ((valkeyReply *)reply)->type == VALKEY_REPLY_ARRAY && + ((valkeyReply *)reply)->elements == 1 && + ((valkeyReply *)reply)->element[0]->type == VALKEY_REPLY_DOUBLE && + fabs(((valkeyReply *)reply)->element[0]->dval - 3.14159265358979323846) < 0.00000001 && + ((valkeyReply *)reply)->element[0]->len == 22 && + strcmp(((valkeyReply *)reply)->element[0]->str, "3.14159265358979323846") == 0); freeReplyObject(reply); valkeyReaderFree(reader); } @@ -923,7 +944,7 @@ static void *vk_calloc_insecure(size_t nmemb, size_t size) { (void)nmemb; (void)size; insecure_calloc_calls++; - return (void*)0xdeadc0de; + return (void *)0xdeadc0de; } static void *vk_realloc_fail(void *ptr, size_t size) { @@ -939,7 +960,7 @@ static char *vk_test_strdup(const char *s) { len = strlen(s); dup = vk_malloc_safe(len + 1); - memcpy(dup,s,len + 1); + memcpy(dup, s, len + 1); return dup; } @@ -970,7 +991,7 @@ static void test_allocator_injection(void) { test("libvalkey calloc wrapper protects against overflow: "); ha.callocFn = vk_calloc_insecure; valkeySetAllocators(&ha); - ptr = vk_calloc((SIZE_MAX / sizeof(void*)) + 3, sizeof(void*)); + ptr = vk_calloc((SIZE_MAX / sizeof(void *)) + 3, sizeof(void *)); test_cond(ptr == NULL && insecure_calloc_calls == 0); // Return allocators to default @@ -1012,12 +1033,11 @@ static void test_blocking_connection_errors(void) { struct timeval tv; test("Returns error when the port is not open: "); - c = valkeyConnect((char*)"localhost", 1); + c = valkeyConnect((char *)"localhost", 1); test_cond(c->err == VALKEY_ERR_IO && - strcmp(c->errstr,"Connection refused") == 0); + strcmp(c->errstr, "Connection refused") == 0); valkeyFree(c); - /* Verify we don't regress from the fix in PR #1180 */ test("We don't clobber connection exception with setsockopt error: "); tv = (struct timeval){.tv_sec = 0, .tv_usec = 500000}; @@ -1029,7 +1049,7 @@ static void test_blocking_connection_errors(void) { valkeyFree(c); test("Returns error when the unix_sock socket path doesn't accept connections: "); - c = valkeyConnectUnix((char*)"/tmp/idontexist.sock"); + c = valkeyConnectUnix((char *)"/tmp/idontexist.sock"); test_cond(c->err == VALKEY_ERR_IO); /* Don't care about the message... */ valkeyFree(c); #endif @@ -1122,7 +1142,7 @@ static void test_resp3_push_handler(valkeyContext *c) { freeReplyObject(reply); test("With no PUSH handler, no replies are lost: "); - assert(valkeyGetReply(c, (void**)&reply) == VALKEY_OK); + assert(valkeyGetReply(c, (void **)&reply) == VALKEY_OK); test_cond(reply != NULL && reply->type == VALKEY_REPLY_STATUS); freeReplyObject(reply); @@ -1210,78 +1230,78 @@ static void test_blocking_connection(struct config config) { c = do_connect(config); test("Is able to deliver commands: "); - reply = valkeyCommand(c,"PING"); + reply = valkeyCommand(c, "PING"); test_cond(reply->type == VALKEY_REPLY_STATUS && - strcasecmp(reply->str,"pong") == 0) + strcasecmp(reply->str, "pong") == 0); freeReplyObject(reply); test("Is a able to send commands verbatim: "); - reply = valkeyCommand(c,"SET foo bar"); - test_cond (reply->type == VALKEY_REPLY_STATUS && - strcasecmp(reply->str,"ok") == 0) + reply = valkeyCommand(c, "SET foo bar"); + test_cond(reply->type == VALKEY_REPLY_STATUS && + strcasecmp(reply->str, "ok") == 0); freeReplyObject(reply); test("%%s String interpolation works: "); - reply = valkeyCommand(c,"SET %s %s","foo","hello world"); + reply = valkeyCommand(c, "SET %s %s", "foo", "hello world"); freeReplyObject(reply); - reply = valkeyCommand(c,"GET foo"); + reply = valkeyCommand(c, "GET foo"); test_cond(reply->type == VALKEY_REPLY_STRING && - strcmp(reply->str,"hello world") == 0); + strcmp(reply->str, "hello world") == 0); freeReplyObject(reply); test("%%b String interpolation works: "); - reply = valkeyCommand(c,"SET %b %b","foo",(size_t)3,"hello\x00world",(size_t)11); + reply = valkeyCommand(c, "SET %b %b", "foo", (size_t)3, "hello\x00world", (size_t)11); freeReplyObject(reply); - reply = valkeyCommand(c,"GET foo"); + reply = valkeyCommand(c, "GET foo"); test_cond(reply->type == VALKEY_REPLY_STRING && - memcmp(reply->str,"hello\x00world",11) == 0) + memcmp(reply->str, "hello\x00world", 11) == 0); test("Binary reply length is correct: "); test_cond(reply->len == 11) - freeReplyObject(reply); + freeReplyObject(reply); test("Can parse nil replies: "); - reply = valkeyCommand(c,"GET nokey"); + reply = valkeyCommand(c, "GET nokey"); test_cond(reply->type == VALKEY_REPLY_NIL) - freeReplyObject(reply); + freeReplyObject(reply); /* test 7 */ test("Can parse integer replies: "); - reply = valkeyCommand(c,"INCR mycounter"); - test_cond(reply->type == VALKEY_REPLY_INTEGER && reply->integer == 1) + reply = valkeyCommand(c, "INCR mycounter"); + test_cond(reply->type == VALKEY_REPLY_INTEGER && reply->integer == 1); freeReplyObject(reply); test("Can parse multi bulk replies: "); - freeReplyObject(valkeyCommand(c,"LPUSH mylist foo")); - freeReplyObject(valkeyCommand(c,"LPUSH mylist bar")); - reply = valkeyCommand(c,"LRANGE mylist 0 -1"); + freeReplyObject(valkeyCommand(c, "LPUSH mylist foo")); + freeReplyObject(valkeyCommand(c, "LPUSH mylist bar")); + reply = valkeyCommand(c, "LRANGE mylist 0 -1"); test_cond(reply->type == VALKEY_REPLY_ARRAY && reply->elements == 2 && - !memcmp(reply->element[0]->str,"bar",3) && - !memcmp(reply->element[1]->str,"foo",3)) + !memcmp(reply->element[0]->str, "bar", 3) && + !memcmp(reply->element[1]->str, "foo", 3)); freeReplyObject(reply); /* m/e with multi bulk reply *before* other reply. * specifically test ordering of reply items to parse. */ test("Can handle nested multi bulk replies: "); - freeReplyObject(valkeyCommand(c,"MULTI")); - freeReplyObject(valkeyCommand(c,"LRANGE mylist 0 -1")); - freeReplyObject(valkeyCommand(c,"PING")); - reply = (valkeyCommand(c,"EXEC")); + freeReplyObject(valkeyCommand(c, "MULTI")); + freeReplyObject(valkeyCommand(c, "LRANGE mylist 0 -1")); + freeReplyObject(valkeyCommand(c, "PING")); + reply = (valkeyCommand(c, "EXEC")); test_cond(reply->type == VALKEY_REPLY_ARRAY && reply->elements == 2 && reply->element[0]->type == VALKEY_REPLY_ARRAY && reply->element[0]->elements == 2 && - !memcmp(reply->element[0]->element[0]->str,"bar",3) && - !memcmp(reply->element[0]->element[1]->str,"foo",3) && + !memcmp(reply->element[0]->element[0]->str, "bar", 3) && + !memcmp(reply->element[0]->element[1]->str, "foo", 3) && reply->element[1]->type == VALKEY_REPLY_STATUS && - strcasecmp(reply->element[1]->str,"pong") == 0); + strcasecmp(reply->element[1]->str, "pong") == 0); freeReplyObject(reply); test("Send command by passing argc/argv: "); const char *argv[3] = {"SET", "foo", "bar"}; size_t argvlen[3] = {3, 3, 3}; - reply = valkeyCommandArgv(c,3,argv,argvlen); + reply = valkeyCommandArgv(c, 3, argv, argvlen); test_cond(reply->type == VALKEY_REPLY_STATUS); freeReplyObject(reply); @@ -1291,7 +1311,8 @@ static void test_blocking_connection(struct config config) { test_cond(valkeyGetReply(c, NULL) == VALKEY_OK); get_server_version(c, &major, NULL); - if (major >= 6) test_resp3_push_handler(c); + if (major >= 6) + test_resp3_push_handler(c); test_resp3_push_options(config); test_privdata_hooks(config); @@ -1325,7 +1346,7 @@ static void test_blocking_connection_timeouts(struct config config) { c = do_connect(config); test("Successfully completes a command when the timeout is not exceeded: "); - reply = valkeyCommand(c,"SET foo fast"); + reply = valkeyCommand(c, "SET foo fast"); freeReplyObject(reply); valkeySetTimeout(c, tv); reply = valkeyCommand(c, "GET foo"); @@ -1389,12 +1410,12 @@ static void test_blocking_io_errors(struct config config) { get_server_version(c, &major, &minor); test("Returns I/O error when the connection is lost: "); - reply = valkeyCommand(c,"QUIT"); + reply = valkeyCommand(c, "QUIT"); if (major > 2 || (major == 2 && minor > 0)) { /* > 2.0 returns OK on QUIT and read() should be issued once more * to know the descriptor is at EOF. */ - test_cond(strcasecmp(reply->str,"OK") == 0 && - valkeyGetReply(c,&_reply) == VALKEY_ERR); + test_cond(strcasecmp(reply->str, "OK") == 0 && + valkeyGetReply(c, &_reply) == VALKEY_ERR); freeReplyObject(reply); } else { test_cond(reply == NULL); @@ -1407,15 +1428,15 @@ static void test_blocking_io_errors(struct config config) { * issued to find out the socket was closed by the server. In both * conditions, the error will be set to EOF. */ assert(c->err == VALKEY_ERR_EOF && - strcmp(c->errstr,"Server closed the connection") == 0); + strcmp(c->errstr, "Server closed the connection") == 0); #endif valkeyFree(c); c = do_connect(config); test("Returns I/O error on socket timeout: "); - struct timeval tv = { 0, 1000 }; - assert(valkeySetTimeout(c,tv) == VALKEY_OK); - int respcode = valkeyGetReply(c,&_reply); + struct timeval tv = {0, 1000}; + assert(valkeySetTimeout(c, tv) == VALKEY_OK); + int respcode = valkeyGetReply(c, &_reply); #ifndef _WIN32 test_cond(respcode == VALKEY_ERR && c->err == VALKEY_ERR_IO && errno == EAGAIN); #else @@ -1434,10 +1455,10 @@ static void test_invalid_timeout_errors(struct config config) { if (config.type == CONN_TCP || config.type == CONN_SSL) { c = valkeyConnectWithTimeout(config.tcp.host, config.tcp.port, config.connect_timeout); - } else if(config.type == CONN_UNIX) { + } else if (config.type == CONN_UNIX) { c = valkeyConnectUnixWithTimeout(config.unix_sock.path, config.connect_timeout); #ifdef VALKEY_TEST_RDMA - } else if(config.type == CONN_RDMA) { + } else if (config.type == CONN_RDMA) { valkeyOptions options = {0}; VALKEY_OPTIONS_SET_RDMA(&options, config.tcp.host, config.tcp.port); options.connect_timeout = &config.connect_timeout; @@ -1452,15 +1473,15 @@ static void test_invalid_timeout_errors(struct config config) { test("Set error when an invalid timeout sec value is used during connect: "); - config.connect_timeout.tv_sec = (((LONG_MAX) - 999) / 1000) + 1; + config.connect_timeout.tv_sec = (((LONG_MAX)-999) / 1000) + 1; config.connect_timeout.tv_usec = 0; if (config.type == CONN_TCP || config.type == CONN_SSL) { c = valkeyConnectWithTimeout(config.tcp.host, config.tcp.port, config.connect_timeout); - } else if(config.type == CONN_UNIX) { + } else if (config.type == CONN_UNIX) { c = valkeyConnectUnixWithTimeout(config.unix_sock.path, config.connect_timeout); #ifdef VALKEY_TEST_RDMA - } else if(config.type == CONN_RDMA) { + } else if (config.type == CONN_RDMA) { valkeyOptions options = {0}; VALKEY_OPTIONS_SET_RDMA(&options, config.tcp.host, config.tcp.port); options.connect_timeout = &config.connect_timeout; @@ -1482,98 +1503,104 @@ static void test_throughput(struct config config) { test("Throughput:\n"); for (i = 0; i < 500; i++) - freeReplyObject(valkeyCommand(c,"LPUSH mylist foo")); + freeReplyObject(valkeyCommand(c, "LPUSH mylist foo")); num = 1000; - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); t1 = usec(); for (i = 0; i < num; i++) { - replies[i] = valkeyCommand(c,"PING"); + replies[i] = valkeyCommand(c, "PING"); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_STATUS); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx PING: %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx PING: %.3fs)\n", num, (t2 - t1) / 1000000.0); - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); t1 = usec(); for (i = 0; i < num; i++) { - replies[i] = valkeyCommand(c,"LRANGE mylist 0 499"); + replies[i] = valkeyCommand(c, "LRANGE mylist 0 499"); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_ARRAY); assert(replies[i] != NULL && replies[i]->elements == 500); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2 - t1) / 1000000.0); - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); t1 = usec(); for (i = 0; i < num; i++) { replies[i] = valkeyCommand(c, "INCRBY incrkey %d", 1000000); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_INTEGER); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx INCRBY: %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx INCRBY: %.3fs)\n", num, (t2 - t1) / 1000000.0); num = 10000; - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); for (i = 0; i < num; i++) - valkeyAppendCommand(c,"PING"); + valkeyAppendCommand(c, "PING"); t1 = usec(); for (i = 0; i < num; i++) { - assert(valkeyGetReply(c, (void*)&replies[i]) == VALKEY_OK); + assert(valkeyGetReply(c, (void *)&replies[i]) == VALKEY_OK); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_STATUS); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2 - t1) / 1000000.0); - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); for (i = 0; i < num; i++) - valkeyAppendCommand(c,"LRANGE mylist 0 499"); + valkeyAppendCommand(c, "LRANGE mylist 0 499"); t1 = usec(); for (i = 0; i < num; i++) { - assert(valkeyGetReply(c, (void*)&replies[i]) == VALKEY_OK); + assert(valkeyGetReply(c, (void *)&replies[i]) == VALKEY_OK); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_ARRAY); assert(replies[i] != NULL && replies[i]->elements == 500); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2 - t1) / 1000000.0); - replies = vk_malloc_safe(sizeof(valkeyReply*)*num); + replies = vk_malloc_safe(sizeof(valkeyReply *) * num); for (i = 0; i < num; i++) - valkeyAppendCommand(c,"INCRBY incrkey %d", 1000000); + valkeyAppendCommand(c, "INCRBY incrkey %d", 1000000); t1 = usec(); for (i = 0; i < num; i++) { - assert(valkeyGetReply(c, (void*)&replies[i]) == VALKEY_OK); + assert(valkeyGetReply(c, (void *)&replies[i]) == VALKEY_OK); assert(replies[i] != NULL && replies[i]->type == VALKEY_REPLY_INTEGER); } t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); + for (i = 0; i < num; i++) + freeReplyObject(replies[i]); vk_free(replies); - printf("\t(%dx INCRBY (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0); + printf("\t(%dx INCRBY (pipelined): %.3fs)\n", num, (t2 - t1) / 1000000.0); disconnect(c, 0); } #ifdef VALKEY_TEST_ASYNC -#pragma GCC diagnostic ignored "-Woverlength-strings" /* required on gcc 4.8.x due to assert statements */ +#pragma GCC diagnostic ignored "-Woverlength-strings" /* required on gcc 4.8.x due to assert statements */ struct event_base *base; typedef struct TestState { valkeyOptions *options; - int checkpoint; - int resp3; - int disconnect; + int checkpoint; + int resp3; + int disconnect; } TestState; /* Helper to disconnect and stop event loop */ @@ -1584,23 +1611,26 @@ void async_disconnect(valkeyAsyncContext *ac) { /* Testcase timeout, will trigger a failure */ void timeout_cb(evutil_socket_t fd, short event, void *arg) { - (void) fd; (void) event; (void) arg; + (void)fd; + (void)event; + (void)arg; printf("Timeout in async testing!\n"); exit(1); } /* Unexpected call, will trigger a failure */ void unexpected_cb(valkeyAsyncContext *ac, void *r, void *privdata) { - (void) ac; (void) r; - printf("Unexpected call: %s\n",(char*)privdata); + (void)ac; + (void)r; + printf("Unexpected call: %s\n", (char *)privdata); exit(1); } /* Helper function to publish a message via own client. */ -void publish_msg(valkeyOptions *options, const char* channel, const char* msg) { +void publish_msg(valkeyOptions *options, const char *channel, const char *msg) { valkeyContext *c = valkeyConnectWithOptions(options); assert(c != NULL); - valkeyReply *reply = valkeyCommand(c,"PUBLISH %s %s",channel,msg); + valkeyReply *reply = valkeyCommand(c, "PUBLISH %s %s", channel, msg); assert(reply->type == VALKEY_REPLY_INTEGER && reply->integer == 1); freeReplyObject(reply); disconnect(c, 0); @@ -1612,7 +1642,8 @@ void integer_cb(valkeyAsyncContext *ac, void *r, void *privdata) { TestState *state = privdata; assert(reply != NULL && reply->type == VALKEY_REPLY_INTEGER); state->checkpoint++; - if (state->disconnect) async_disconnect(ac); + if (state->disconnect) + async_disconnect(ac); } /* Subscribe callback for test_pubsub_handling and test_pubsub_handling_resp3: @@ -1626,26 +1657,26 @@ void subscribe_cb(valkeyAsyncContext *ac, void *r, void *privdata) { reply->type == (state->resp3 ? VALKEY_REPLY_PUSH : VALKEY_REPLY_ARRAY) && reply->elements == 3); - if (strcmp(reply->element[0]->str,"subscribe") == 0) { - assert(strcmp(reply->element[1]->str,"mychannel") == 0 && + if (strcmp(reply->element[0]->str, "subscribe") == 0) { + assert(strcmp(reply->element[1]->str, "mychannel") == 0 && reply->element[2]->str == NULL); - publish_msg(state->options,"mychannel","Hello!"); - } else if (strcmp(reply->element[0]->str,"message") == 0) { - assert(strcmp(reply->element[1]->str,"mychannel") == 0 && - strcmp(reply->element[2]->str,"Hello!") == 0); + publish_msg(state->options, "mychannel", "Hello!"); + } else if (strcmp(reply->element[0]->str, "message") == 0) { + assert(strcmp(reply->element[1]->str, "mychannel") == 0 && + strcmp(reply->element[2]->str, "Hello!") == 0); state->checkpoint++; /* Unsubscribe after receiving the published message. Send unsubscribe * which should call the callback registered during subscribe */ - valkeyAsyncCommand(ac,unexpected_cb, - (void*)"unsubscribe should call subscribe_cb()", - "unsubscribe"); + valkeyAsyncCommand(ac, unexpected_cb, + (void *)"unsubscribe should call subscribe_cb()", + "unsubscribe"); /* Send a regular command after unsubscribing, then disconnect */ state->disconnect = 1; - valkeyAsyncCommand(ac,integer_cb,state,"LPUSH mylist foo"); + valkeyAsyncCommand(ac, integer_cb, state, "LPUSH mylist foo"); - } else if (strcmp(reply->element[0]->str,"unsubscribe") == 0) { - assert(strcmp(reply->element[1]->str,"mychannel") == 0 && + } else if (strcmp(reply->element[0]->str, "unsubscribe") == 0) { + assert(strcmp(reply->element[1]->str, "mychannel") == 0 && reply->element[2]->str == NULL); } else { printf("Unexpected pubsub command: %s\n", reply->element[0]->str); @@ -1659,12 +1690,13 @@ void array_cb(valkeyAsyncContext *ac, void *r, void *privdata) { TestState *state = privdata; assert(reply != NULL && reply->type == VALKEY_REPLY_ARRAY); state->checkpoint++; - if (state->disconnect) async_disconnect(ac); + if (state->disconnect) + async_disconnect(ac); } /* Expect a NULL reply */ void null_cb(valkeyAsyncContext *ac, void *r, void *privdata) { - (void) ac; + (void)ac; assert(r == NULL); TestState *state = privdata; state->checkpoint++; @@ -1677,7 +1709,7 @@ static void test_pubsub_handling(struct config config) { struct event *timeout = evtimer_new(base, timeout_cb, NULL); assert(timeout != NULL); - evtimer_assign(timeout,base,timeout_cb,NULL); + evtimer_assign(timeout, base, timeout_cb, NULL); struct timeval timeout_tv = {.tv_sec = 10}; evtimer_add(timeout, &timeout_tv); @@ -1685,14 +1717,14 @@ static void test_pubsub_handling(struct config config) { valkeyOptions options = get_server_tcp_options(config); valkeyAsyncContext *ac = valkeyAsyncConnectWithOptions(&options); assert(ac != NULL && ac->err == 0); - valkeyLibeventAttach(ac,base); + valkeyLibeventAttach(ac, base); /* Start subscribe */ TestState state = {.options = &options}; - valkeyAsyncCommand(ac,subscribe_cb,&state,"subscribe mychannel"); + valkeyAsyncCommand(ac, subscribe_cb, &state, "subscribe mychannel"); /* Make sure non-subscribe commands are handled */ - valkeyAsyncCommand(ac,array_cb,&state,"PING"); + valkeyAsyncCommand(ac, array_cb, &state, "PING"); /* Start event dispatching loop */ test_cond(event_base_dispatch(base) == 0); @@ -1705,7 +1737,8 @@ static void test_pubsub_handling(struct config config) { /* Unexpected push message, will trigger a failure */ void unexpected_push_cb(valkeyAsyncContext *ac, void *r) { - (void) ac; (void) r; + (void)ac; + (void)r; printf("Unexpected call to the PUSH callback!\n"); exit(1); } @@ -1717,7 +1750,7 @@ static void test_pubsub_handling_resp3(struct config config) { struct event *timeout = evtimer_new(base, timeout_cb, NULL); assert(timeout != NULL); - evtimer_assign(timeout,base,timeout_cb,NULL); + evtimer_assign(timeout, base, timeout_cb, NULL); struct timeval timeout_tv = {.tv_sec = 10}; evtimer_add(timeout, &timeout_tv); @@ -1725,24 +1758,24 @@ static void test_pubsub_handling_resp3(struct config config) { valkeyOptions options = get_server_tcp_options(config); valkeyAsyncContext *ac = valkeyAsyncConnectWithOptions(&options); assert(ac != NULL && ac->err == 0); - valkeyLibeventAttach(ac,base); + valkeyLibeventAttach(ac, base); /* Not expecting any push messages in this test */ valkeyAsyncSetPushCallback(ac, unexpected_push_cb); /* Switch protocol */ - valkeyAsyncCommand(ac,NULL,NULL,"HELLO 3"); + valkeyAsyncCommand(ac, NULL, NULL, "HELLO 3"); /* Start subscribe */ TestState state = {.options = &options, .resp3 = 1}; - valkeyAsyncCommand(ac,subscribe_cb,&state,"subscribe mychannel"); + valkeyAsyncCommand(ac, subscribe_cb, &state, "subscribe mychannel"); /* Make sure non-subscribe commands are handled in RESP3 */ - valkeyAsyncCommand(ac,integer_cb,&state,"LPUSH mylist foo"); - valkeyAsyncCommand(ac,integer_cb,&state,"LPUSH mylist foo"); - valkeyAsyncCommand(ac,integer_cb,&state,"LPUSH mylist foo"); + valkeyAsyncCommand(ac, integer_cb, &state, "LPUSH mylist foo"); + valkeyAsyncCommand(ac, integer_cb, &state, "LPUSH mylist foo"); + valkeyAsyncCommand(ac, integer_cb, &state, "LPUSH mylist foo"); /* Handle an array with 3 elements as a non-subscribe command */ - valkeyAsyncCommand(ac,array_cb,&state,"LRANGE mylist 0 2"); + valkeyAsyncCommand(ac, array_cb, &state, "LRANGE mylist 0 2"); /* Start event dispatching loop */ test_cond(event_base_dispatch(base) == 0); @@ -1772,19 +1805,19 @@ void subscribe_with_timeout_cb(valkeyAsyncContext *ac, void *r, void *privdata) assert(reply->type == (state->resp3 ? VALKEY_REPLY_PUSH : VALKEY_REPLY_ARRAY) && reply->elements == 3); - if (strcmp(reply->element[0]->str,"subscribe") == 0) { - assert(strcmp(reply->element[1]->str,"mychannel") == 0 && + if (strcmp(reply->element[0]->str, "subscribe") == 0) { + assert(strcmp(reply->element[1]->str, "mychannel") == 0 && reply->element[2]->str == NULL); - publish_msg(state->options,"mychannel","Hello!"); + publish_msg(state->options, "mychannel", "Hello!"); state->checkpoint++; - } else if (strcmp(reply->element[0]->str,"message") == 0) { - assert(strcmp(reply->element[1]->str,"mychannel") == 0 && - strcmp(reply->element[2]->str,"Hello!") == 0); + } else if (strcmp(reply->element[0]->str, "message") == 0) { + assert(strcmp(reply->element[1]->str, "mychannel") == 0 && + strcmp(reply->element[2]->str, "Hello!") == 0); state->checkpoint++; /* Send a command that will trigger a timeout */ - valkeyAsyncCommand(ac,null_cb,state,"DEBUG SLEEP 3"); - valkeyAsyncCommand(ac,null_cb,state,"LPUSH mylist foo"); + valkeyAsyncCommand(ac, null_cb, state, "DEBUG SLEEP 3"); + valkeyAsyncCommand(ac, null_cb, state, "LPUSH mylist foo"); } else { printf("Unexpected pubsub command: %s\n", reply->element[0]->str); exit(1); @@ -1795,32 +1828,32 @@ static void test_command_timeout_during_pubsub(struct config config) { test("Command timeout during Pub/Sub: "); /* Setup event dispatcher with a testcase timeout */ base = event_base_new(); - struct event *timeout = evtimer_new(base,timeout_cb,NULL); + struct event *timeout = evtimer_new(base, timeout_cb, NULL); assert(timeout != NULL); - evtimer_assign(timeout,base,timeout_cb,NULL); + evtimer_assign(timeout, base, timeout_cb, NULL); struct timeval timeout_tv = {.tv_sec = 10}; - evtimer_add(timeout,&timeout_tv); + evtimer_add(timeout, &timeout_tv); /* Connect */ valkeyOptions options = get_server_tcp_options(config); valkeyAsyncContext *ac = valkeyAsyncConnectWithOptions(&options); assert(ac != NULL && ac->err == 0); - valkeyLibeventAttach(ac,base); + valkeyLibeventAttach(ac, base); /* Configure a command timout */ struct timeval command_timeout = {.tv_sec = 2}; - valkeyAsyncSetTimeout(ac,command_timeout); + valkeyAsyncSetTimeout(ac, command_timeout); /* Not expecting any push messages in this test */ - valkeyAsyncSetPushCallback(ac,unexpected_push_cb); + valkeyAsyncSetPushCallback(ac, unexpected_push_cb); /* Switch protocol */ - valkeyAsyncCommand(ac,NULL,NULL,"HELLO 3"); + valkeyAsyncCommand(ac, NULL, NULL, "HELLO 3"); /* Start subscribe */ TestState state = {.options = &options, .resp3 = 1}; - valkeyAsyncCommand(ac,subscribe_with_timeout_cb,&state,"subscribe mychannel"); + valkeyAsyncCommand(ac, subscribe_with_timeout_cb, &state, "subscribe mychannel"); /* Start event dispatching loop */ assert(event_base_dispatch(base) == 0); @@ -1839,28 +1872,28 @@ void subscribe_channel_a_cb(valkeyAsyncContext *ac, void *r, void *privdata) { assert(reply != NULL && reply->type == VALKEY_REPLY_ARRAY && reply->elements == 3); - if (strcmp(reply->element[0]->str,"subscribe") == 0) { - assert(strcmp(reply->element[1]->str,"A") == 0); - publish_msg(state->options,"A","Hello!"); + if (strcmp(reply->element[0]->str, "subscribe") == 0) { + assert(strcmp(reply->element[1]->str, "A") == 0); + publish_msg(state->options, "A", "Hello!"); state->checkpoint++; - } else if (strcmp(reply->element[0]->str,"message") == 0) { - assert(strcmp(reply->element[1]->str,"A") == 0 && - strcmp(reply->element[2]->str,"Hello!") == 0); + } else if (strcmp(reply->element[0]->str, "message") == 0) { + assert(strcmp(reply->element[1]->str, "A") == 0 && + strcmp(reply->element[2]->str, "Hello!") == 0); state->checkpoint++; /* Unsubscribe to channels, including channel X & Z which we don't subscribe to */ - valkeyAsyncCommand(ac,unexpected_cb, - (void*)"unsubscribe should not call unexpected_cb()", - "unsubscribe B X A A Z"); + valkeyAsyncCommand(ac, unexpected_cb, + (void *)"unsubscribe should not call unexpected_cb()", + "unsubscribe B X A A Z"); /* Unsubscribe to patterns, none which we subscribe to */ - valkeyAsyncCommand(ac,unexpected_cb, - (void*)"punsubscribe should not call unexpected_cb()", - "punsubscribe"); + valkeyAsyncCommand(ac, unexpected_cb, + (void *)"punsubscribe should not call unexpected_cb()", + "punsubscribe"); /* Send a regular command after unsubscribing, then disconnect */ state->disconnect = 1; - valkeyAsyncCommand(ac,integer_cb,state,"LPUSH mylist foo"); - } else if (strcmp(reply->element[0]->str,"unsubscribe") == 0) { - assert(strcmp(reply->element[1]->str,"A") == 0); + valkeyAsyncCommand(ac, integer_cb, state, "LPUSH mylist foo"); + } else if (strcmp(reply->element[0]->str, "unsubscribe") == 0) { + assert(strcmp(reply->element[1]->str, "A") == 0); state->checkpoint++; } else { printf("Unexpected pubsub command: %s\n", reply->element[0]->str); @@ -1877,11 +1910,11 @@ void subscribe_channel_b_cb(valkeyAsyncContext *ac, void *r, void *privdata) { assert(reply != NULL && reply->type == VALKEY_REPLY_ARRAY && reply->elements == 3); - if (strcmp(reply->element[0]->str,"subscribe") == 0) { - assert(strcmp(reply->element[1]->str,"B") == 0); + if (strcmp(reply->element[0]->str, "subscribe") == 0) { + assert(strcmp(reply->element[1]->str, "B") == 0); state->checkpoint++; - } else if (strcmp(reply->element[0]->str,"unsubscribe") == 0) { - assert(strcmp(reply->element[1]->str,"B") == 0); + } else if (strcmp(reply->element[0]->str, "unsubscribe") == 0) { + assert(strcmp(reply->element[1]->str, "B") == 0); state->checkpoint++; } else { printf("Unexpected pubsub command: %s\n", reply->element[0]->str); @@ -1900,26 +1933,26 @@ static void test_pubsub_multiple_channels(struct config config) { test("Subscribe to multiple channels: "); /* Setup event dispatcher with a testcase timeout */ base = event_base_new(); - struct event *timeout = evtimer_new(base,timeout_cb,NULL); + struct event *timeout = evtimer_new(base, timeout_cb, NULL); assert(timeout != NULL); - evtimer_assign(timeout,base,timeout_cb,NULL); + evtimer_assign(timeout, base, timeout_cb, NULL); struct timeval timeout_tv = {.tv_sec = 10}; - evtimer_add(timeout,&timeout_tv); + evtimer_add(timeout, &timeout_tv); /* Connect */ valkeyOptions options = get_server_tcp_options(config); valkeyAsyncContext *ac = valkeyAsyncConnectWithOptions(&options); assert(ac != NULL && ac->err == 0); - valkeyLibeventAttach(ac,base); + valkeyLibeventAttach(ac, base); /* Not expecting any push messages in this test */ - valkeyAsyncSetPushCallback(ac,unexpected_push_cb); + valkeyAsyncSetPushCallback(ac, unexpected_push_cb); /* Start subscribing to two channels */ TestState state = {.options = &options}; - valkeyAsyncCommand(ac,subscribe_channel_a_cb,&state,"subscribe A"); - valkeyAsyncCommand(ac,subscribe_channel_b_cb,&state,"subscribe B"); + valkeyAsyncCommand(ac, subscribe_channel_a_cb, &state, "subscribe A"); + valkeyAsyncCommand(ac, subscribe_channel_b_cb, &state, "subscribe B"); /* Start event dispatching loop */ assert(event_base_dispatch(base) == 0); @@ -1948,24 +1981,24 @@ void monitor_cb(valkeyAsyncContext *ac, void *r, void *privdata) { /* Response from MONITOR */ valkeyContext *c = valkeyConnectWithOptions(state->options); assert(c != NULL); - valkeyReply *reply = valkeyCommand(c,"SET first 1"); + valkeyReply *reply = valkeyCommand(c, "SET first 1"); assert(reply->type == VALKEY_REPLY_STATUS); freeReplyObject(reply); valkeyFree(c); } else if (state->checkpoint == 2) { /* Response for monitored command 'SET first 1' */ - assert(strstr(reply->str,"first") != NULL); + assert(strstr(reply->str, "first") != NULL); valkeyContext *c = valkeyConnectWithOptions(state->options); assert(c != NULL); - valkeyReply *reply = valkeyCommand(c,"SET second 2"); + valkeyReply *reply = valkeyCommand(c, "SET second 2"); assert(reply->type == VALKEY_REPLY_STATUS); freeReplyObject(reply); valkeyFree(c); } else if (state->checkpoint == 3) { /* Response for monitored command 'SET second 2' */ - assert(strstr(reply->str,"second") != NULL); + assert(strstr(reply->str, "second") != NULL); /* Send QUIT to disconnect */ - valkeyAsyncCommand(ac,NULL,NULL,"QUIT"); + valkeyAsyncCommand(ac, NULL, NULL, "QUIT"); } } @@ -1980,7 +2013,7 @@ static void test_monitor(struct config config) { struct event *timeout = evtimer_new(base, timeout_cb, NULL); assert(timeout != NULL); - evtimer_assign(timeout,base,timeout_cb,NULL); + evtimer_assign(timeout, base, timeout_cb, NULL); struct timeval timeout_tv = {.tv_sec = 10}; evtimer_add(timeout, &timeout_tv); @@ -1988,14 +2021,14 @@ static void test_monitor(struct config config) { valkeyOptions options = get_server_tcp_options(config); valkeyAsyncContext *ac = valkeyAsyncConnectWithOptions(&options); assert(ac != NULL && ac->err == 0); - valkeyLibeventAttach(ac,base); + valkeyLibeventAttach(ac, base); /* Not expecting any push messages in this test */ - valkeyAsyncSetPushCallback(ac,unexpected_push_cb); + valkeyAsyncSetPushCallback(ac, unexpected_push_cb); /* Start monitor */ TestState state = {.options = &options}; - valkeyAsyncCommand(ac,monitor_cb,&state,"monitor"); + valkeyAsyncCommand(ac, monitor_cb, &state, "monitor"); /* Start event dispatching loop */ test_cond(event_base_dispatch(base) == 0); @@ -2010,15 +2043,14 @@ static void test_monitor(struct config config) { /* tests for async api using polling adapter, requires no extra libraries*/ /* enum for the test cases, the callbacks have different logic based on them */ -typedef enum astest_no -{ - ASTEST_CONNECT=0, +typedef enum astest_no { + ASTEST_CONNECT = 0, ASTEST_CONN_TIMEOUT, ASTEST_PINGPONG, ASTEST_PINGPONG_TIMEOUT, ASTEST_ISSUE_931, ASTEST_ISSUE_931_PING -}astest_no; +} astest_no; /* a static context for the async tests */ struct _astest { @@ -2037,13 +2069,12 @@ struct _astest { static struct _astest astest; /* async callbacks */ -static void asCleanup(void* data) -{ +static void asCleanup(void *data) { struct _astest *t = (struct _astest *)data; t->ac = NULL; } -static void commandCallback(struct valkeyAsyncContext *ac, void* _reply, void* _privdata); +static void commandCallback(struct valkeyAsyncContext *ac, void *_reply, void *_privdata); static void connectCallback(valkeyAsyncContext *c, int status) { struct _astest *t = (struct _astest *)c->data; @@ -2058,14 +2089,12 @@ static void connectCallback(valkeyAsyncContext *c, int status) { if (t->testno == ASTEST_ISSUE_931) { /* disconnect again */ valkeyAsyncDisconnect(c); - } - else if (t->testno == ASTEST_ISSUE_931_PING) - { + } else if (t->testno == ASTEST_ISSUE_931_PING) { valkeyAsyncCommand(c, commandCallback, NULL, "PING"); } } static void disconnectCallback(const valkeyAsyncContext *c, int status) { - assert(c->data == (void*)&astest); + assert(c->data == (void *)&astest); assert(astest.disconnects == 0); astest.err = c->err; strcpy(astest.errstr, c->errstr); @@ -2074,23 +2103,20 @@ static void disconnectCallback(const valkeyAsyncContext *c, int status) { astest.connected = 0; } -static void commandCallback(struct valkeyAsyncContext *ac, void* _reply, void* _privdata) -{ - valkeyReply *reply = (valkeyReply*)_reply; +static void commandCallback(struct valkeyAsyncContext *ac, void *_reply, void *_privdata) { + valkeyReply *reply = (valkeyReply *)_reply; struct _astest *t = (struct _astest *)ac->data; assert(t == &astest); (void)_privdata; t->err = ac->err; strcpy(t->errstr, ac->errstr); t->counter++; - if (t->testno == ASTEST_PINGPONG ||t->testno == ASTEST_ISSUE_931_PING) - { + if (t->testno == ASTEST_PINGPONG || t->testno == ASTEST_ISSUE_931_PING) { assert(reply != NULL && reply->type == VALKEY_REPLY_STATUS && strcmp(reply->str, "PONG") == 0); t->pongs++; valkeyAsyncFree(ac); } - if (t->testno == ASTEST_PINGPONG_TIMEOUT) - { + if (t->testno == ASTEST_PINGPONG_TIMEOUT) { /* two ping pongs */ assert(reply != NULL && reply->type == VALKEY_REPLY_STATUS && strcmp(reply->str, "PONG") == 0); t->pongs++; @@ -2103,8 +2129,7 @@ static void commandCallback(struct valkeyAsyncContext *ac, void* _reply, void* _ } } -static valkeyAsyncContext *do_aconnect(struct config config, astest_no testno) -{ +static valkeyAsyncContext *do_aconnect(struct config config, astest_no testno) { valkeyOptions options = {0}; memset(&astest, 0, sizeof(astest)); @@ -2147,11 +2172,12 @@ static void as_printerr(void) { printf("Async err %d : %s\n", astest.err, astest.errstr); } -#define ASASSERT(e) do { \ - if (!(e)) \ - as_printerr(); \ - assert(e); \ -} while (0); +#define ASASSERT(e) \ + do { \ + if (!(e)) \ + as_printerr(); \ + assert(e); \ + } while (0); static void test_async_polling(struct config config) { int status; @@ -2161,7 +2187,7 @@ static void test_async_polling(struct config config) { test("Async connect: "); c = do_aconnect(config, ASTEST_CONNECT); assert(c); - while(astest.connected == 0) + while (astest.connected == 0) valkeyPollTick(c, 0.1); assert(astest.connects == 1); ASASSERT(astest.connect_status == VALKEY_OK); @@ -2178,12 +2204,12 @@ static void test_async_polling(struct config config) { if (config.type == CONN_TCP || config.type == CONN_SSL) { /* timeout can only be simulated with network */ test("Async connect timeout: "); - config.tcp.host = "192.168.254.254"; /* blackhole ip */ + config.tcp.host = "192.168.254.254"; /* blackhole ip */ config.connect_timeout.tv_usec = 100000; c = do_aconnect(config, ASTEST_CONN_TIMEOUT); assert(c); assert(c->err == 0); - while(astest.connected == 0) + while (astest.connected == 0) valkeyPollTick(c, 0.1); assert(astest.connected == -1); /* @@ -2198,11 +2224,11 @@ static void test_async_polling(struct config config) { /* Test a ping/pong after connection */ test("Async PING/PONG: "); c = do_aconnect(config, ASTEST_PINGPONG); - while(astest.connected == 0) + while (astest.connected == 0) valkeyPollTick(c, 0.1); status = valkeyAsyncCommand(c, commandCallback, NULL, "PING"); assert(status == VALKEY_OK); - while(astest.ac) + while (astest.ac) valkeyPollTick(c, 0.1); test_cond(astest.pongs == 1); @@ -2211,13 +2237,13 @@ static void test_async_polling(struct config config) { test("Async PING/PONG after connect timeout: "); config.connect_timeout.tv_usec = 10000; /* 10ms */ c = do_aconnect(config, ASTEST_PINGPONG_TIMEOUT); - while(astest.connected == 0) + while (astest.connected == 0) valkeyPollTick(c, 0.1); /* sleep 0.1 s, allowing old timeout to arrive */ millisleep(10); status = valkeyAsyncCommand(c, commandCallback, NULL, "PING"); assert(status == VALKEY_OK); - while(astest.ac) + while (astest.ac) valkeyPollTick(c, 0.1); test_cond(astest.pongs == 2); config = defaultconfig; @@ -2226,7 +2252,7 @@ static void test_async_polling(struct config config) { /* Test disconnect from an on_connect callback */ test("Disconnect from onConnected callback (Issue #931): "); c = do_aconnect(config, ASTEST_ISSUE_931); - while(astest.disconnects == 0) + while (astest.disconnects == 0) valkeyPollTick(c, 0.1); assert(astest.connected == 0); assert(astest.connects == 1); @@ -2236,7 +2262,7 @@ static void test_async_polling(struct config config) { test("Ping/Pong from onConnected callback (Issue #931): "); c = do_aconnect(config, ASTEST_ISSUE_931_PING); /* connect callback issues ping, response callback destroys context */ - while(astest.ac) + while (astest.ac) valkeyPollTick(c, 0.1); assert(astest.connected == 0); assert(astest.connects == 1); @@ -2249,11 +2275,10 @@ int main(int argc, char **argv) { struct config cfg = { .tcp = { .host = "127.0.0.1", - .port = 6379 - }, + .port = 6379}, .unix_sock = { - .path = "/tmp/valkey.sock" - } + .path = "/tmp/valkey.sock", + }, }; int throughput = 1; int test_inherit_fd = 1; @@ -2261,50 +2286,61 @@ int main(int argc, char **argv) { int test_unix_socket; /* Parse command line options. */ - argv++; argc--; + argv++; + argc--; while (argc) { - if (argc >= 2 && !strcmp(argv[0],"-h")) { - argv++; argc--; + if (argc >= 2 && !strcmp(argv[0], "-h")) { + argv++; + argc--; cfg.tcp.host = argv[0]; - } else if (argc >= 2 && !strcmp(argv[0],"-p")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "-p")) { + argv++; + argc--; cfg.tcp.port = atoi(argv[0]); - } else if (argc >= 2 && !strcmp(argv[0],"-s")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "-s")) { + argv++; + argc--; cfg.unix_sock.path = argv[0]; - } else if (argc >= 1 && !strcmp(argv[0],"--skip-throughput")) { + } else if (argc >= 1 && !strcmp(argv[0], "--skip-throughput")) { throughput = 0; - } else if (argc >= 1 && !strcmp(argv[0],"--skip-inherit-fd")) { + } else if (argc >= 1 && !strcmp(argv[0], "--skip-inherit-fd")) { test_inherit_fd = 0; - } else if (argc >= 1 && !strcmp(argv[0],"--skips-as-fails")) { + } else if (argc >= 1 && !strcmp(argv[0], "--skips-as-fails")) { skips_as_fails = 1; #ifdef VALKEY_TEST_SSL - } else if (argc >= 2 && !strcmp(argv[0],"--ssl-port")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "--ssl-port")) { + argv++; + argc--; cfg.ssl.port = atoi(argv[0]); - } else if (argc >= 2 && !strcmp(argv[0],"--ssl-host")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "--ssl-host")) { + argv++; + argc--; cfg.ssl.host = argv[0]; - } else if (argc >= 2 && !strcmp(argv[0],"--ssl-ca-cert")) { - argv++; argc--; - cfg.ssl.ca_cert = argv[0]; - } else if (argc >= 2 && !strcmp(argv[0],"--ssl-cert")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "--ssl-ca-cert")) { + argv++; + argc--; + cfg.ssl.ca_cert = argv[0]; + } else if (argc >= 2 && !strcmp(argv[0], "--ssl-cert")) { + argv++; + argc--; cfg.ssl.cert = argv[0]; - } else if (argc >= 2 && !strcmp(argv[0],"--ssl-key")) { - argv++; argc--; + } else if (argc >= 2 && !strcmp(argv[0], "--ssl-key")) { + argv++; + argc--; cfg.ssl.key = argv[0]; #endif #ifdef VALKEY_TEST_RDMA - } else if (argc >= 1 && !strcmp(argv[0],"--rdma-addr")) { - argv++; argc--; + } else if (argc >= 1 && !strcmp(argv[0], "--rdma-addr")) { + argv++; + argc--; cfg.rdma.host = argv[0]; #endif } else { fprintf(stderr, "Invalid argument: %s\n", argv[0]); exit(1); } - argv++; argc--; + argv++; + argc--; } #ifndef _WIN32 @@ -2333,7 +2369,8 @@ int main(int argc, char **argv) { test_invalid_timeout_errors(cfg); test_append_formatted_commands(cfg); test_tcp_options(cfg); - if (throughput) test_throughput(cfg); + if (throughput) + test_throughput(cfg); printf("\nTesting against Unix socket connection (%s): ", cfg.unix_sock.path); if (test_unix_socket) { @@ -2344,7 +2381,8 @@ int main(int argc, char **argv) { test_blocking_io_errors(cfg); test_invalid_timeout_errors(cfg); test_unix_keepalive(cfg); - if (throughput) test_throughput(cfg); + if (throughput) + test_throughput(cfg); } else { test_skipped(); } @@ -2364,7 +2402,8 @@ int main(int argc, char **argv) { test_blocking_io_errors(cfg); test_invalid_timeout_errors(cfg); test_append_formatted_commands(cfg); - if (throughput) test_throughput(cfg); + if (throughput) + test_throughput(cfg); valkeyFreeSSLContext(_ssl_ctx); _ssl_ctx = NULL; @@ -2383,7 +2422,8 @@ int main(int argc, char **argv) { test_blocking_io_errors(cfg); test_invalid_timeout_errors(cfg); test_append_formatted_commands(cfg); - if (throughput) test_throughput(cfg); + if (throughput) + test_throughput(cfg); } #endif diff --git a/tests/clusterclient.c b/tests/clusterclient.c index 8e51740b..c7945c60 100644 --- a/tests/clusterclient.c +++ b/tests/clusterclient.c @@ -15,6 +15,7 @@ */ #include "valkeycluster.h" + #include #include #include diff --git a/tests/clusterclient_async.c b/tests/clusterclient_async.c index 121e2849..52a586c1 100644 --- a/tests/clusterclient_async.c +++ b/tests/clusterclient_async.c @@ -38,6 +38,7 @@ #include "adapters/libevent.h" #include "test_utils.h" #include "valkeycluster.h" + #include #include #include diff --git a/tests/clusterclient_reconnect_async.c b/tests/clusterclient_reconnect_async.c index 3b76e9d6..f4af4961 100644 --- a/tests/clusterclient_reconnect_async.c +++ b/tests/clusterclient_reconnect_async.c @@ -12,6 +12,7 @@ #include "adapters/libevent.h" #include "test_utils.h" #include "valkeycluster.h" + #include #include #include diff --git a/tests/ct_async.c b/tests/ct_async.c index 27eae289..6854b342 100644 --- a/tests/ct_async.c +++ b/tests/ct_async.c @@ -1,6 +1,7 @@ #include "adapters/libevent.h" #include "test_utils.h" #include "valkeycluster.h" + #include #include #include diff --git a/tests/ct_async_glib.c b/tests/ct_async_glib.c index 88bbdb47..30e117f8 100644 --- a/tests/ct_async_glib.c +++ b/tests/ct_async_glib.c @@ -1,6 +1,7 @@ #include "adapters/glib.h" #include "test_utils.h" #include "valkeycluster.h" + #include #define CLUSTER_NODE "127.0.0.1:7000" @@ -53,10 +54,10 @@ int main(int argc, char **argv) { valkeyClusterAsyncSetConnectCallback(acc, connectCallback); valkeyClusterAsyncSetDisconnectCallback(acc, disconnectCallback); - status = valkeyClusterAsyncCommand(acc, setCallback, (char*)"id", "SET key value"); + status = valkeyClusterAsyncCommand(acc, setCallback, (char *)"id", "SET key value"); ASSERT_MSG(status == VALKEY_OK, acc->errstr); - status = valkeyClusterAsyncCommand(acc, getCallback, (char*)"id", "GET key"); + status = valkeyClusterAsyncCommand(acc, getCallback, (char *)"id", "GET key"); ASSERT_MSG(status == VALKEY_OK, acc->errstr); g_main_loop_run(mainloop); diff --git a/tests/ct_async_libev.c b/tests/ct_async_libev.c index 27559e5b..39cdcbc4 100644 --- a/tests/ct_async_libev.c +++ b/tests/ct_async_libev.c @@ -1,6 +1,7 @@ #include "adapters/libev.h" #include "test_utils.h" #include "valkeycluster.h" + #include #define CLUSTER_NODE "127.0.0.1:7000" diff --git a/tests/ct_async_libuv.c b/tests/ct_async_libuv.c index 8b9e9148..de40e313 100644 --- a/tests/ct_async_libuv.c +++ b/tests/ct_async_libuv.c @@ -1,6 +1,7 @@ #include "adapters/libuv.h" #include "test_utils.h" #include "valkeycluster.h" + #include #define CLUSTER_NODE "127.0.0.1:7000" diff --git a/tests/ct_commands.c b/tests/ct_commands.c index 3767eb4b..0ce6efe8 100644 --- a/tests/ct_commands.c +++ b/tests/ct_commands.c @@ -1,5 +1,6 @@ #include "test_utils.h" #include "valkeycluster.h" + #include #include #include diff --git a/tests/ct_connection_ipv6.c b/tests/ct_connection_ipv6.c index d5c36662..d89d4e6d 100644 --- a/tests/ct_connection_ipv6.c +++ b/tests/ct_connection_ipv6.c @@ -1,5 +1,6 @@ #include "test_utils.h" #include "valkeycluster.h" + #include #include #include diff --git a/tests/ct_out_of_memory_handling.c b/tests/ct_out_of_memory_handling.c index e6ef09dc..e3057d30 100644 --- a/tests/ct_out_of_memory_handling.c +++ b/tests/ct_out_of_memory_handling.c @@ -27,6 +27,7 @@ #include "adapters/libevent.h" #include "test_utils.h" #include "valkeycluster.h" + #include #include #include @@ -202,7 +203,7 @@ void test_alloc_failure_handling(void) { valkeyReply *reply; const char *cmd = "SET key value"; - valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char*)"key"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char *)"key"); assert(node); // OOM failing commands @@ -265,7 +266,7 @@ void test_alloc_failure_handling(void) { valkeyReply *reply; const char *cmd = "SET foo one"; - valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char*)"foo"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char *)"foo"); assert(node); // OOM failing appends @@ -313,8 +314,8 @@ void test_alloc_failure_handling(void) { prepare_allocation_test(cc, 1000); /* Get the source information for the migration. */ - unsigned int slot = valkeyClusterGetSlotByKey((char*)"foo"); - valkeyClusterNode *srcNode = valkeyClusterGetNodeByKey(cc, (char*)"foo"); + unsigned int slot = valkeyClusterGetSlotByKey((char *)"foo"); + valkeyClusterNode *srcNode = valkeyClusterGetNodeByKey(cc, (char *)"foo"); int srcPort = srcNode->port; /* Get a destination node to migrate the slot to. */ @@ -371,7 +372,7 @@ void test_alloc_failure_handling(void) { * allowing a high number of allocations. */ prepare_allocation_test(cc, 1000); /* Fetch the nodes again, in case the slotmap has been reloaded. */ - srcNode = valkeyClusterGetNodeByKey(cc, (char*)"foo"); + srcNode = valkeyClusterGetNodeByKey(cc, (char *)"foo"); dstNode = getNodeByPort(cc, dstPort); reply = valkeyClusterCommandToNode( cc, srcNode, "CLUSTER SETSLOT %d NODE %s", slot, replyDstId->str); diff --git a/tests/ct_specific_nodes.c b/tests/ct_specific_nodes.c index c5c43b23..e75a8c8e 100644 --- a/tests/ct_specific_nodes.c +++ b/tests/ct_specific_nodes.c @@ -45,7 +45,7 @@ void test_command_to_all_nodes(valkeyClusterContext *cc) { void test_transaction(valkeyClusterContext *cc) { - valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char*)"foo"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char *)"foo"); assert(node); valkeyReply *reply; @@ -73,7 +73,7 @@ void test_streams(valkeyClusterContext *cc) { char *id; /* Get the node that handles given stream */ - valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char*)"mystream"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char *)"mystream"); assert(node); /* Preparation: remove old stream/key */ @@ -82,7 +82,7 @@ void test_streams(valkeyClusterContext *cc) { freeReplyObject(reply); /* Query wrong node */ - valkeyClusterNode *wrongNode = valkeyClusterGetNodeByKey(cc, (char*)"otherstream"); + valkeyClusterNode *wrongNode = valkeyClusterGetNodeByKey(cc, (char *)"otherstream"); assert(node != wrongNode); reply = valkeyClusterCommandToNode(cc, wrongNode, "XLEN mystream"); CHECK_REPLY_ERROR(cc, reply, "MOVED"); @@ -235,7 +235,7 @@ void test_pipeline_transaction(valkeyClusterContext *cc) { int status; valkeyReply *reply; - valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char*)"foo"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(cc, (char *)"foo"); assert(node); status = valkeyClusterAppendCommandToNode(cc, node, "MULTI"); @@ -487,7 +487,7 @@ void test_async_transaction(void) { status = valkeyClusterLibeventAttach(acc, base); assert(status == VALKEY_OK); - valkeyClusterNode *node = valkeyClusterGetNodeByKey(acc->cc, (char*)"foo"); + valkeyClusterNode *node = valkeyClusterGetNodeByKey(acc->cc, (char *)"foo"); assert(node); ExpectedResult r1 = {.type = VALKEY_REPLY_STATUS, .str = "OK"}; diff --git a/tests/test_utils.c b/tests/test_utils.c index 760ca67d..8153afa4 100644 --- a/tests/test_utils.c +++ b/tests/test_utils.c @@ -1,6 +1,7 @@ +#include "test_utils.h" + #include "valkeycluster.h" -#include "test_utils.h" #include #include diff --git a/tests/test_utils.h b/tests/test_utils.h index 9475f130..c3411f59 100644 --- a/tests/test_utils.h +++ b/tests/test_utils.h @@ -5,72 +5,72 @@ #include /* For struct timeval */ #endif -#define ASSERT_MSG(_x, _msg) \ - if (!(_x)) { \ - fprintf(stderr, "ERROR: %s (%s)\n", _msg, #_x); \ - assert(_x); \ +#define ASSERT_MSG(_x, _msg) \ + if (!(_x)) { \ + fprintf(stderr, "ERROR: %s (%s)\n", _msg, #_x); \ + assert(_x); \ } -#define CHECK_REPLY(_ctx, _reply) \ - if (!(_reply)) { \ - ASSERT_MSG(_reply, _ctx->errstr); \ +#define CHECK_REPLY(_ctx, _reply) \ + if (!(_reply)) { \ + ASSERT_MSG(_reply, _ctx->errstr); \ } -#define CHECK_REPLY_TYPE(_reply, _type) \ +#define CHECK_REPLY_TYPE(_reply, _type) \ { ASSERT_MSG((_reply->type == _type), "Reply type incorrect"); } -#define CHECK_REPLY_STATUS(_ctx, _reply, _str) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_STATUS); \ - ASSERT_MSG((strcmp(_reply->str, _str) == 0), _ctx->errstr); \ +#define CHECK_REPLY_STATUS(_ctx, _reply, _str) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_STATUS); \ + ASSERT_MSG((strcmp(_reply->str, _str) == 0), _ctx->errstr); \ } -#define CHECK_REPLY_OK(_ctx, _reply) \ +#define CHECK_REPLY_OK(_ctx, _reply) \ { CHECK_REPLY_STATUS(_ctx, _reply, "OK") } -#define CHECK_REPLY_QUEUED(_ctx, _reply) \ +#define CHECK_REPLY_QUEUED(_ctx, _reply) \ { CHECK_REPLY_STATUS(_ctx, _reply, "QUEUED") } -#define CHECK_REPLY_INT(_ctx, _reply, _value) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_INTEGER); \ - ASSERT_MSG((_reply->integer == _value), _ctx->errstr); \ +#define CHECK_REPLY_INT(_ctx, _reply, _value) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_INTEGER); \ + ASSERT_MSG((_reply->integer == _value), _ctx->errstr); \ } -#define CHECK_REPLY_STR(_ctx, _reply, _str) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_STRING); \ - ASSERT_MSG((strcmp(_reply->str, _str) == 0), _ctx->errstr); \ +#define CHECK_REPLY_STR(_ctx, _reply, _str) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_STRING); \ + ASSERT_MSG((strcmp(_reply->str, _str) == 0), _ctx->errstr); \ } -#define CHECK_REPLY_ARRAY(_ctx, _reply, _num_of_elements) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_ARRAY); \ - ASSERT_MSG(_reply->elements == _num_of_elements, _ctx->errstr); \ +#define CHECK_REPLY_ARRAY(_ctx, _reply, _num_of_elements) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_ARRAY); \ + ASSERT_MSG(_reply->elements == _num_of_elements, _ctx->errstr); \ } -#define CHECK_REPLY_NIL(_ctx, _reply) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_NIL); \ +#define CHECK_REPLY_NIL(_ctx, _reply) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_NIL); \ } -#define CHECK_REPLY_ERROR(_ctx, _reply, _str) \ - { \ - CHECK_REPLY(_ctx, _reply); \ - CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_ERROR); \ - ASSERT_MSG((strncmp(_reply->str, _str, strlen(_str)) == 0), \ - _ctx->errstr); \ +#define CHECK_REPLY_ERROR(_ctx, _reply, _str) \ + { \ + CHECK_REPLY(_ctx, _reply); \ + CHECK_REPLY_TYPE(_reply, VALKEY_REPLY_ERROR); \ + ASSERT_MSG((strncmp(_reply->str, _str, strlen(_str)) == 0), \ + _ctx->errstr); \ } -#define ASSERT_STR_EQ(_s1, _s2) \ +#define ASSERT_STR_EQ(_s1, _s2) \ { assert(strcmp(_s1, _s2) == 0); } -#define ASSERT_STR_STARTS_WITH(_s1, _s2) \ +#define ASSERT_STR_STARTS_WITH(_s1, _s2) \ { assert(strncmp(_s1, _s2, strlen(_s2)) == 0); } struct valkeyClusterContext; diff --git a/tests/ut_parse_cmd.c b/tests/ut_parse_cmd.c index d95b92c7..7f628483 100644 --- a/tests/ut_parse_cmd.c +++ b/tests/ut_parse_cmd.c @@ -1,9 +1,11 @@ /* Some unit tests that don't require Valkey to be running. */ +#include "win32.h" + #include "command.h" #include "test_utils.h" #include "valkeycluster.h" -#include "win32.h" + #include #include #include @@ -28,9 +30,9 @@ void check_key(const char *key, struct cmd *command, const char *file, int line) } /* Checks that a command (struct cmd *) has the given key (string). */ -#define ASSERT_KEY(command, key) \ - do { \ - check_key(key, command, __FILE__, __LINE__); \ +#define ASSERT_KEY(command, key) \ + do { \ + check_key(key, command, __FILE__, __LINE__); \ } while (0) void test_valkey_parse_error_nonresp(void) {