From 9a46c5afc46a4a5383b501bb3a2d6f53123b2f28 Mon Sep 17 00:00:00 2001
From: Ronsor <ronsor@ronsor.pw>
Date: Fri, 23 Dec 2022 19:18:10 -0700
Subject: [PATCH] Add a new example showing how to use hiredis.

---
 examples/examples.mk |  1 +
 examples/hiredis.c   | 55 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 56 insertions(+)
 create mode 100644 examples/hiredis.c

diff --git a/examples/examples.mk b/examples/examples.mk
index 26317f1e8..ab28ad6b7 100644
--- a/examples/examples.mk
+++ b/examples/examples.mk
@@ -80,6 +80,7 @@ EXAMPLES_DIRECTDEPS =								\
 	THIRD_PARTY_LIBCXX							\
 	THIRD_PARTY_LINENOISE							\
 	THIRD_PARTY_LUA								\
+	THIRD_PARTY_HIREDIS							\
 	THIRD_PARTY_MBEDTLS							\
 	THIRD_PARTY_MUSL							\
 	THIRD_PARTY_NSYNC							\
diff --git a/examples/hiredis.c b/examples/hiredis.c
new file mode 100644
index 000000000..5f4954bb0
--- /dev/null
+++ b/examples/hiredis.c
@@ -0,0 +1,55 @@
+#if 0
+/*─────────────────────────────────────────────────────────────────╗
+│ To the extent possible under law, Justine Tunney has waived      │
+│ all copyright and related or neighboring rights to this file,    │
+│ as it is written in the following disclaimers:                   │
+│   • http://unlicense.org/                                        │
+│   • http://creativecommons.org/publicdomain/zero/1.0/            │
+╚─────────────────────────────────────────────────────────────────*/
+#endif
+#include "libc/runtime/runtime.h"
+#include "libc/fmt/conv.h"
+#include "libc/fmt/fmt.h"
+#include "libc/stdio/stdio.h"
+#include "libc/str/str.h"
+#include "third_party/hiredis/hiredis.h"
+
+/**
+ * @fileoverview Demo of using hiredis to connect to a Redis server
+ */
+
+int main(int argc, char *argv[]) {
+  if (argc < 3 || argc > 5) {
+    fprintf(stderr, "Usage: %s HOST PORT [KEY] [VALUE]\n", argv[0]);
+    exit(1);
+  }
+
+  bool setValue = (argc == 5), getValue = (argc == 4);
+
+  redisContext *c = redisConnect(argv[1], atoi(argv[2]));
+  if (c == NULL || c->err) {
+    if (c) {
+      fprintf(stderr, "Connection error: %s\n", c->errstr);
+      redisFree(c);
+    } else {
+      fputs("Failed to allocate redis context\n", stderr);
+    }
+    exit(1);
+  }
+
+  redisReply *reply;
+  if (!setValue && !getValue) {
+    reply = redisCommand(c, "PING");
+    printf("PING: %s\n", reply->str);
+  } else if (setValue) {
+    reply = redisCommand(c, "SET %s %s", argv[3], argv[4]);
+    printf("SET: %s\n", reply->str);
+  } else {
+    reply = redisCommand(c, "GET %s", argv[3]);
+    printf("GET: %s\n", reply->str);
+  }
+
+  freeReplyObject(reply);
+  redisFree(c);
+  return 0;
+}