diff --git a/src/Makefile b/src/Makefile index 648127a2..86e0b3fe 100644 --- a/src/Makefile +++ b/src/Makefile @@ -14,23 +14,33 @@ release_hdr := $(shell sh -c './mkreleasehdr.sh') uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not') OPTIMIZATION?=-O2 -DEPENDENCY_TARGETS=hiredis linenoise lua geohash-int +DEPENDENCY_TARGETS=hiredis linenoise lua +NODEPS:=clean distclean # Default settings STD=-std=c99 -pedantic -DREDIS_STATIC='' -WARN=-Wall -W +WARN=-Wall -W -Wno-missing-field-initializers OPT=$(OPTIMIZATION) PREFIX?=/usr/local INSTALL_BIN=$(PREFIX)/bin INSTALL=install -# Default allocator +# Default allocator defaults to Jemalloc if it's not an ARM +MALLOC=libc +ifneq ($(uname_M),armv6l) +ifneq ($(uname_M),armv7l) ifeq ($(uname_S),Linux) MALLOC=jemalloc -else - MALLOC=libc +endif +endif +endif + +# To get ARM stack traces if Redis crashes we need a special C flag. +ifneq (,$(findstring armv,$(uname_M))) + CFLAGS+=-funwind-tables endif # Backwards compatibility for selecting an allocator @@ -53,29 +63,46 @@ endif # Override default settings if possible -include .make-settings -FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS) -I../deps/geohash-int +FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS) FINAL_LDFLAGS=$(LDFLAGS) $(REDIS_LDFLAGS) $(DEBUG) FINAL_LIBS=-lm DEBUG=-g -ggdb ifeq ($(uname_S),SunOS) # SunOS + ifneq ($(@@),32bit) + CFLAGS+= -m64 + LDFLAGS+= -m64 + endif + DEBUG=-g + DEBUG_FLAGS=-g + export CFLAGS LDFLAGS DEBUG DEBUG_FLAGS INSTALL=cp -pf FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6 FINAL_LIBS+= -ldl -lnsl -lsocket -lresolv -lpthread -lrt else ifeq ($(uname_S),Darwin) - # Darwin (nothing to do) + # Darwin + FINAL_LIBS+= -ldl else ifeq ($(uname_S),AIX) # AIX FINAL_LDFLAGS+= -Wl,-bexpall - FINAL_LIBS+= -pthread -lcrypt -lbsd - + FINAL_LIBS+=-ldl -pthread -lcrypt -lbsd +else +ifeq ($(uname_S),OpenBSD) + # OpenBSD + FINAL_LIBS+= -lpthread +else +ifeq ($(uname_S),FreeBSD) + # FreeBSD + FINAL_LIBS+= -lpthread else # All the other OSes (notably Linux) FINAL_LDFLAGS+= -rdynamic - FINAL_LIBS+= -pthread + FINAL_LIBS+=-ldl -pthread +endif +endif endif endif endif @@ -95,7 +122,7 @@ endif ifeq ($(MALLOC),jemalloc) DEPENDENCY_TARGETS+= jemalloc FINAL_CFLAGS+= -DUSE_JEMALLOC -I../deps/jemalloc/include - FINAL_LIBS+= ../deps/jemalloc/lib/libjemalloc.a -ldl + FINAL_LIBS+= ../deps/jemalloc/lib/libjemalloc.a endif REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS) @@ -117,31 +144,28 @@ endif REDIS_SERVER_NAME=redis-server REDIS_SENTINEL_NAME=redis-sentinel -REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o geo.o -REDIS_GEOHASH_OBJ=../deps/geohash-int/geohash.o ../deps/geohash-int/geohash_helper.o +REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o REDIS_CLI_NAME=redis-cli REDIS_CLI_OBJ=anet.o adlist.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o REDIS_BENCHMARK_NAME=redis-benchmark REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o zmalloc.o redis-benchmark.o REDIS_CHECK_RDB_NAME=redis-check-rdb REDIS_CHECK_AOF_NAME=redis-check-aof -REDIS_CHECK_AOF_OBJ=redis-check-aof.o all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) @echo "" @echo "Hint: It's a good idea to run 'make test' ;)" @echo "" +Makefile.dep: + -$(REDIS_CC) -MM *.c > Makefile.dep 2> /dev/null || true + +ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) +-include Makefile.dep +endif + .PHONY: all -# Deps (use make dep to generate this) -include Makefile.dep - -dep: - $(REDIS_CC) -MM *.c > Makefile.dep - -.PHONY: dep - persist-settings: distclean echo STD=$(STD) >> .make-settings echo WARN=$(WARN) >> .make-settings @@ -172,7 +196,7 @@ endif # redis-server $(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ) - $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(REDIS_GEOHASH_OBJ) $(FINAL_LIBS) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(FINAL_LIBS) # redis-sentinel $(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME) @@ -182,6 +206,10 @@ $(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME): $(REDIS_SERVER_NAME) $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME) +# redis-check-aof +$(REDIS_CHECK_AOF_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME) + # redis-cli $(REDIS_CLI_NAME): $(REDIS_CLI_OBJ) $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS) @@ -190,9 +218,8 @@ $(REDIS_CLI_NAME): $(REDIS_CLI_OBJ) $(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ) $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS) -# redis-check-aof -$(REDIS_CHECK_AOF_NAME): $(REDIS_CHECK_AOF_OBJ) - $(REDIS_LD) -o $@ $^ $(FINAL_LIBS) +dict-benchmark: dict.c zmalloc.c sds.c siphash.c + $(REDIS_CC) $(FINAL_CFLAGS) $^ -D DICT_BENCHMARK_MAIN -o $@ $(FINAL_LIBS) # Because the jemalloc.h header is generated as a part of the jemalloc build, # building it should complete before building any other object. Instead of @@ -201,7 +228,7 @@ $(REDIS_CHECK_AOF_NAME): $(REDIS_CHECK_AOF_OBJ) $(REDIS_CC) -c $< clean: - rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html + rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark .PHONY: clean @@ -226,7 +253,7 @@ lcov: @genhtml --legend -o lcov-html redis.info test-sds: sds.c sds.h - $(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN -o /tmp/sds_test + $(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN $(FINAL_LIBS) -o /tmp/sds_test /tmp/sds_test .PHONY: lcov @@ -249,6 +276,9 @@ noopt: valgrind: $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" +helgrind: + $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" CFLAGS="-D__ATOMIC_VAR_FORCE_SYNC_MACROS" + src/help.h: @../utils/generate-command-help.rb > help.h diff --git a/src/config.c b/src/config.c index cb273649..b6e77e3e 100644 --- a/src/config.c +++ b/src/config.c @@ -314,7 +314,6 @@ void loadServerConfigFromString(char *config) { setLogFile(server.logfile); #endif } - fclose(logfp); } } else if (!strcasecmp(argv[0],"always-show-logo") && argc == 2) { @@ -702,7 +701,7 @@ void loadServerConfigFromString(char *config) { goto loaderr; } } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) { - server.slowlog_max_len = (PORT_ULONG)(strtol(argv[1],NULL,10)); WIN_PORT_FIX /* cast (PORT_ULONG) */ + server.slowlog_max_len = (PORT_ULONG)(strtoll(argv[1],NULL,10)); WIN_PORT_FIX /* cast (PORT_ULONG) */ } else if (!strcasecmp(argv[0],"client-output-buffer-limit") && argc == 5) { @@ -1235,6 +1234,10 @@ void configSetCommand(client *c) { } freeMemoryIfNeeded(); } + } config_set_memory_field( + "proto-max-bulk-len",server.proto_max_bulk_len) { + } config_set_memory_field( + "client-query-buffer-limit",server.client_max_querybuf_len) { } config_set_memory_field("repl-backlog-size",ll) { resizeReplicationBacklog(ll); } config_set_memory_field("auto-aof-rewrite-min-size",ll) { diff --git a/src/config.h b/src/config.h index 8ceea26b..681c22d3 100644 --- a/src/config.h +++ b/src/config.h @@ -145,7 +145,7 @@ void setproctitle(const char *fmt, ...); #else #define LITTLE_ENDIAN 1234 /* least-significant byte first (vax, pc) */ #define BIG_ENDIAN 4321 /* most-significant byte first (IBM, net) */ -#define PDP_ENDIAN 3412 /* LSB first in word, MSW first in PORT_LONG (pdp)*/ +#define PDP_ENDIAN 3412 /* LSB first in word, MSW first in long (pdp)*/ #if defined(__i386__) || defined(__x86_64__) || defined(__amd64__) || \ defined(vax) || defined(ns32000) || defined(sun386) || \ diff --git a/src/db.c b/src/db.c index d53f541d..25970623 100644 --- a/src/db.c +++ b/src/db.c @@ -435,7 +435,7 @@ void flushallCommand(client *c) { server.dirty += emptyDb(-1,flags,NULL); addReply(c,shared.ok); if (server.rdb_child_pid != -1) { - IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid, SIGUSR1)); + IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid,SIGUSR1)); rdbRemoveTempFile(server.rdb_child_pid); } if (server.saveparamslen > 0) { @@ -584,7 +584,7 @@ void scanCallback(void *privdata, const dictEntry *de) { int parseScanCursorOrReply(client *c, robj *o, PORT_ULONG *cursor) { char *eptr; - /* Use strtoul() because we need an *unsigned* PORT_LONG, so + /* Use strtoul() because we need an *unsigned* long, so * getLongLongFromObject() does not cover the whole cursor space. */ errno = 0; *cursor = strtoul(o->ptr, &eptr, 10); diff --git a/src/debug.c b/src/debug.c index 8069eb64..157625f2 100644 --- a/src/debug.c +++ b/src/debug.c @@ -56,7 +56,7 @@ /* ================================= Debugging ============================== */ -/* Compute the sha1 of string at 's' with 'len' bytes PORT_LONG. +/* Compute the sha1 of string at 's' with 'len' bytes long. * The SHA1 is then xored against the string pointed by digest. * Since xor is commutative, this operation is used in order to * "add" digests relative to unordered elements. @@ -1044,7 +1044,7 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) { "Redis %s crashed by signal: %d", REDIS_VERSION, sig); if (eip != NULL) { serverLog(LL_WARNING, - "Crashed running the instuction at: %p", eip); + "Crashed running the instruction at: %p", eip); } if (sig == SIGSEGV || sig == SIGBUS) { serverLog(LL_WARNING, @@ -1143,7 +1143,7 @@ void serverLogHexDump(int level, char *descr, void *value, size_t len) { unsigned char *v = value; char charset[] = "0123456789abcdef"; - serverLog(level,"%s (hexdump of %Iu bytes):", descr, len); + serverLog(level,"%s (hexdump of %Iu bytes):", descr, len); WIN_PORT_FIX /* %zu -> %Iu */ b = buf; while(len) { b[0] = charset[(*v)>>4]; diff --git a/src/dict.c b/src/dict.c index 362eb361..6b1cf446 100644 --- a/src/dict.c +++ b/src/dict.c @@ -308,7 +308,7 @@ int dictAdd(dict *d, void *key, void *val) */ dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing) { - int index; + PORT_LONG index; dictEntry *entry; dictht *ht; @@ -636,7 +636,7 @@ dictEntry *dictGetRandomKey(dict *d) do { /* We are sure there are no elements in indexes from 0 * to rehashidx-1 */ - h = (PORT_ULONG) (d->rehashidx + (random() % (d->ht[0].size + WIN_PORT_FIX /* cast (unsigned int) */ + h = (PORT_ULONG) (d->rehashidx + (random() % (d->ht[0].size + WIN_PORT_FIX /* cast (PORT_ULONG) */ d->ht[1].size - d->rehashidx))); he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] : @@ -960,7 +960,7 @@ static PORT_ULONG _dictNextPower(PORT_ULONG size) { PORT_ULONG i = DICT_HT_INITIAL_SIZE; - if (size >= PORT_LONG_MAX) return PORT_LONG_MAX; + if (size >= PORT_LONG_MAX) return PORT_LONG_MAX + 1LU; while(1) { if (i >= size) return i; diff --git a/src/evict.c b/src/evict.c index de441960..cd505fee 100644 --- a/src/evict.c +++ b/src/evict.c @@ -412,7 +412,7 @@ int freeMemoryIfNeeded(void) { latencyStartMonitor(latency); while (mem_freed < mem_tofree) { int j, k, i, keys_freed = 0; - static int next_db = 0; + static unsigned int next_db = 0; sds bestkey = NULL; int bestdbid; redisDb *db; diff --git a/src/expire.c b/src/expire.c index b1e50e1b..7a0cc337 100644 --- a/src/expire.c +++ b/src/expire.c @@ -103,7 +103,7 @@ void activeExpireCycle(int type) { int j, iteration = 0; int dbs_per_call = CRON_DBS_PER_CALL; - PORT_LONGLONG start = ustime(), timelimit; + PORT_LONGLONG start = ustime(), timelimit, elapsed; /* When clients are paused the dataset should be static not just from the * POV of clients not being able to write, but also from the POV of @@ -111,7 +111,7 @@ void activeExpireCycle(int type) { if (clientsArePaused()) return; if (type == ACTIVE_EXPIRE_CYCLE_FAST) { - /* Don't start a fast cycle if the previous cycle did not exited + /* Don't start a fast cycle if the previous cycle did not exit * for time limt. Also don't repeat a fast cycle for the same period * as the fast cycle total duration itself. */ if (!timelimit_exit) return; @@ -140,7 +140,13 @@ void activeExpireCycle(int type) { if (type == ACTIVE_EXPIRE_CYCLE_FAST) timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */ - for (j = 0; j < dbs_per_call; j++) { + /* Accumulate some global stats as we expire keys, to have some idea + * about the number of keys that are already logically expired, but still + * existing inside the database. */ + long total_sampled = 0; + long total_expired = 0; + + for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) { int expired; redisDb *db = server.db+(current_db % server.dbnum); @@ -155,6 +161,7 @@ void activeExpireCycle(int type) { PORT_ULONG num, slots; PORT_LONGLONG now, ttl_sum; int ttl_samples; + iteration++; /* If there is nothing to expire try next DB ASAP. */ if ((num = dictSize(db->expires)) == 0) { @@ -191,7 +198,9 @@ void activeExpireCycle(int type) { ttl_sum += ttl; ttl_samples++; } + total_sampled++; } + total_expired += expired; /* Update the average TTL stats for this database. */ if (ttl_samples) { @@ -207,18 +216,31 @@ void activeExpireCycle(int type) { /* We can't block forever here even if there are many keys to * expire. So after a given amount of milliseconds return to the * caller waiting for the other active expire cycle. */ - iteration++; if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */ - PORT_LONGLONG elapsed = ustime()-start; - - latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); - if (elapsed > timelimit) timelimit_exit = 1; + elapsed = ustime()-start; + if (elapsed > timelimit) { + timelimit_exit = 1; + server.stat_expired_time_cap_reached_count++; + break; + } } - if (timelimit_exit) return; /* We don't repeat the cycle if there are less than 25% of keys * found expired in the current DB. */ } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4); } + + elapsed = ustime()-start; + latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); + + /* Update our estimate of keys existing but yet to be expired. + * Running average with this sample accounting for 5%. */ + double current_perc; + if (total_sampled) { + current_perc = (double)total_expired/total_sampled; + } else + current_perc = 0; + server.stat_expired_stale_perc = (current_perc*0.05)+ + (server.stat_expired_stale_perc*0.95); } /*----------------------------------------------------------------------------- diff --git a/src/hyperloglog.c b/src/hyperloglog.c index f57d6269..1530ca7e 100644 --- a/src/hyperloglog.c +++ b/src/hyperloglog.c @@ -611,11 +611,7 @@ int hllSparseToDense(robj *o) { } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); - if ((runlen + idx) > HLL_REGISTERS) break; /* Overflow. */ - if ((runlen + idx) > HLL_REGISTERS) { - sdsfree(dense); - return C_ERR; - } + if ((runlen + idx) > HLL_REGISTERS) break; /* Overflow. */ while(runlen--) { HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval); idx++; @@ -701,7 +697,7 @@ int hllSparseSet(robj *o, PORT_LONG index, uint8_t count) { p += oplen; first += span; } - if (span == 0) return -1; /* Invalid format. */ + if (span == 0 || p >= end) return -1; /* Invalid format. */ next = HLL_SPARSE_IS_XZERO(p) ? p+2 : p+1; if (next >= end) next = NULL; @@ -1086,10 +1082,8 @@ int hllMerge(uint8_t *max, robj *hll) { } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); - if ((runlen + i) > HLL_REGISTERS) - return C_ERR; - if ((runlen + i) > HLL_REGISTERS) break; /* Overflow. */ - while(runlen--) { + if ((runlen + i) > HLL_REGISTERS) break; /* Overflow. */ + while(runlen--) { if (regval > max[i]) max[i] = (uint8_t)regval; WIN_PORT_FIX /* cast (uint8_t) */ i++; } diff --git a/src/intset.c b/src/intset.c index 57dcde14..90feecb5 100644 --- a/src/intset.c +++ b/src/intset.c @@ -39,13 +39,13 @@ #include "zmalloc.h" #include "endianconv.h" - /* Note that these encodings are ordered, so: - * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */ +/* Note that these encodings are ordered, so: + * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */ #define INTSET_ENC_INT16 (sizeof(int16_t)) #define INTSET_ENC_INT32 (sizeof(int32_t)) #define INTSET_ENC_INT64 (sizeof(int64_t)) - /* Return the required encoding for the provided value. */ +/* Return the required encoding for the provided value. */ static uint8_t _intsetValueEncoding(int64_t v) { if (v < INT32_MIN || v > INT32_MAX) return INTSET_ENC_INT64; @@ -62,17 +62,15 @@ static int64_t _intsetGetEncoded(intset *is, int pos, uint8_t enc) { int16_t v16; if (enc == INTSET_ENC_INT64) { - memcpy(&v64, ((int64_t*) is->contents) + pos, sizeof(v64)); + memcpy(&v64,((int64_t*)is->contents)+pos,sizeof(v64)); memrev64ifbe(&v64); return v64; - } - else if (enc == INTSET_ENC_INT32) { - memcpy(&v32, ((int32_t*) is->contents) + pos, sizeof(v32)); + } else if (enc == INTSET_ENC_INT32) { + memcpy(&v32,((int32_t*)is->contents)+pos,sizeof(v32)); memrev32ifbe(&v32); return v32; - } - else { - memcpy(&v16, ((int16_t*) is->contents) + pos, sizeof(v16)); + } else { + memcpy(&v16,((int16_t*)is->contents)+pos,sizeof(v16)); memrev16ifbe(&v16); return v16; } @@ -80,7 +78,7 @@ static int64_t _intsetGetEncoded(intset *is, int pos, uint8_t enc) { /* Return the value at pos, using the configured encoding. */ static int64_t _intsetGet(intset *is, int pos) { - return _intsetGetEncoded(is, pos, intrev32ifbe(is->encoding)); + return _intsetGetEncoded(is,pos,intrev32ifbe(is->encoding)); } /* Set the value at pos, using the configured encoding. */ @@ -88,16 +86,14 @@ static void _intsetSet(intset *is, int pos, int64_t value) { uint32_t encoding = intrev32ifbe(is->encoding); if (encoding == INTSET_ENC_INT64) { - ((int64_t*) is->contents)[pos] = value; - memrev64ifbe(((int64_t*) is->contents) + pos); - } - else if (encoding == INTSET_ENC_INT32) { - ((int32_t*) is->contents)[pos] = (int32_t) value; WIN_PORT_FIX /* cast (int32_t) */ - memrev32ifbe(((int32_t*) is->contents) + pos); - } - else { - ((int16_t*) is->contents)[pos] = (int16_t) value; WIN_PORT_FIX /* cast (int16_t) */ - memrev16ifbe(((int16_t*) is->contents) + pos); + ((int64_t*)is->contents)[pos] = value; + memrev64ifbe(((int64_t*)is->contents)+pos); + } else if (encoding == INTSET_ENC_INT32) { + ((int32_t*)is->contents)[pos] = (int32_t)value; WIN_PORT_FIX /* cast (int32_t) */ + memrev32ifbe(((int32_t*)is->contents)+pos); + } else { + ((int16_t*)is->contents)[pos] = (int16_t)value; WIN_PORT_FIX /* cast (int16_t) */ + memrev16ifbe(((int16_t*)is->contents)+pos); } } @@ -112,7 +108,7 @@ intset *intsetNew(void) { /* Resize the intset */ static intset *intsetResize(intset *is, uint32_t len) { uint32_t size = len*intrev32ifbe(is->encoding); - is = zrealloc(is, sizeof(intset) + size); + is = zrealloc(is,sizeof(intset)+size); return is; } @@ -121,37 +117,33 @@ static intset *intsetResize(intset *is, uint32_t len) { * the value is not present in the intset and sets "pos" to the position * where "value" can be inserted. */ static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) { - int min = 0, max = intrev32ifbe(is->length) - 1, mid = -1; + int min = 0, max = intrev32ifbe(is->length)-1, mid = -1; int64_t cur = -1; /* The value can never be found when the set is empty */ if (intrev32ifbe(is->length) == 0) { if (pos) *pos = 0; return 0; - } - else { + } else { /* Check for the case where we know we cannot find the value, * but do know the insert position. */ - if (value > _intsetGet(is, intrev32ifbe(is->length) - 1)) { + if (value > _intsetGet(is,intrev32ifbe(is->length)-1)) { if (pos) *pos = intrev32ifbe(is->length); return 0; - } - else if (value < _intsetGet(is, 0)) { + } else if (value < _intsetGet(is,0)) { if (pos) *pos = 0; return 0; } } - while (max >= min) { - mid = ((unsigned int) min + (unsigned int) max) >> 1; - cur = _intsetGet(is, mid); + while(max >= min) { + mid = ((unsigned int)min + (unsigned int)max) >> 1; + cur = _intsetGet(is,mid); if (value > cur) { - min = mid + 1; - } - else if (value < cur) { - max = mid - 1; - } - else { + min = mid+1; + } else if (value < cur) { + max = mid-1; + } else { break; } } @@ -159,8 +151,7 @@ static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) { if (value == cur) { if (pos) *pos = mid; return 1; - } - else { + } else { if (pos) *pos = min; return 0; } @@ -175,44 +166,42 @@ static intset *intsetUpgradeAndAdd(intset *is, int64_t value) { /* First set new encoding and resize */ is->encoding = intrev32ifbe(newenc); - is = intsetResize(is, intrev32ifbe(is->length) + 1); + is = intsetResize(is,intrev32ifbe(is->length)+1); /* Upgrade back-to-front so we don't overwrite values. * Note that the "prepend" variable is used to make sure we have an empty * space at either the beginning or the end of the intset. */ - while (length--) - _intsetSet(is, length + prepend, _intsetGetEncoded(is, length, curenc)); + while(length--) + _intsetSet(is,length+prepend,_intsetGetEncoded(is,length,curenc)); /* Set the value at the beginning or the end. */ if (prepend) - _intsetSet(is, 0, value); + _intsetSet(is,0,value); else - _intsetSet(is, intrev32ifbe(is->length), value); - is->length = intrev32ifbe(intrev32ifbe(is->length) + 1); + _intsetSet(is,intrev32ifbe(is->length),value); + is->length = intrev32ifbe(intrev32ifbe(is->length)+1); return is; } static void intsetMoveTail(intset *is, uint32_t from, uint32_t to) { void *src, *dst; - uint32_t bytes = intrev32ifbe(is->length) - from; + uint32_t bytes = intrev32ifbe(is->length)-from; uint32_t encoding = intrev32ifbe(is->encoding); if (encoding == INTSET_ENC_INT64) { - src = (int64_t*) is->contents + from; - dst = (int64_t*) is->contents + to; + src = (int64_t*)is->contents+from; + dst = (int64_t*)is->contents+to; bytes *= sizeof(int64_t); - } - else if (encoding == INTSET_ENC_INT32) { - src = (int32_t*) is->contents + from; - dst = (int32_t*) is->contents + to; + } else if (encoding == INTSET_ENC_INT32) { + src = (int32_t*)is->contents+from; + dst = (int32_t*)is->contents+to; bytes *= sizeof(int32_t); - } - else { - src = (int16_t*) is->contents + from; - dst = (int16_t*) is->contents + to; + } else { + src = (int16_t*)is->contents+from; + dst = (int16_t*)is->contents+to; bytes *= sizeof(int16_t); } - memmove(dst, src, bytes); + memmove(dst,src,bytes); } /* Insert an integer in the intset */ @@ -226,23 +215,22 @@ intset *intsetAdd(intset *is, int64_t value, uint8_t *success) { * because it lies outside the range of existing values. */ if (valenc > intrev32ifbe(is->encoding)) { /* This always succeeds, so we don't need to curry *success. */ - return intsetUpgradeAndAdd(is, value); - } - else { + return intsetUpgradeAndAdd(is,value); + } else { /* Abort if the value is already present in the set. * This call will populate "pos" with the right position to insert * the value when it cannot be found. */ - if (intsetSearch(is, value, &pos)) { + if (intsetSearch(is,value,&pos)) { if (success) *success = 0; return is; } - is = intsetResize(is, intrev32ifbe(is->length) + 1); - if (pos < intrev32ifbe(is->length)) intsetMoveTail(is, pos, pos + 1); + is = intsetResize(is,intrev32ifbe(is->length)+1); + if (pos < intrev32ifbe(is->length)) intsetMoveTail(is,pos,pos+1); } - _intsetSet(is, pos, value); - is->length = intrev32ifbe(intrev32ifbe(is->length) + 1); + _intsetSet(is,pos,value); + is->length = intrev32ifbe(intrev32ifbe(is->length)+1); return is; } @@ -252,16 +240,16 @@ intset *intsetRemove(intset *is, int64_t value, int *success) { uint32_t pos; if (success) *success = 0; - if (valenc <= intrev32ifbe(is->encoding) && intsetSearch(is, value, &pos)) { + if (valenc <= intrev32ifbe(is->encoding) && intsetSearch(is,value,&pos)) { uint32_t len = intrev32ifbe(is->length); /* We know we can delete */ if (success) *success = 1; /* Overwrite value with tail and update length */ - if (pos < (len - 1)) intsetMoveTail(is, pos + 1, pos); - is = intsetResize(is, len - 1); - is->length = intrev32ifbe(len - 1); + if (pos < (len-1)) intsetMoveTail(is,pos+1,pos); + is = intsetResize(is,len-1); + is->length = intrev32ifbe(len-1); } return is; } @@ -269,19 +257,19 @@ intset *intsetRemove(intset *is, int64_t value, int *success) { /* Determine whether a value belongs to this set */ uint8_t intsetFind(intset *is, int64_t value) { uint8_t valenc = _intsetValueEncoding(value); - return valenc <= intrev32ifbe(is->encoding) && intsetSearch(is, value, NULL); + return valenc <= intrev32ifbe(is->encoding) && intsetSearch(is,value,NULL); } /* Return random member */ int64_t intsetRandom(intset *is) { - return _intsetGet(is, rand() % intrev32ifbe(is->length)); + return _intsetGet(is,rand()%intrev32ifbe(is->length)); } /* Get the value at the given position. When this position is * out of range the function returns 0, when in range it returns 1. */ uint8_t intsetGet(intset *is, uint32_t pos, int64_t *value) { if (pos < intrev32ifbe(is->length)) { - *value = _intsetGet(is, pos); + *value = _intsetGet(is,pos); return 1; } return 0; @@ -294,7 +282,7 @@ uint32_t intsetLen(const intset *is) { /* Return intset blob size in bytes. */ size_t intsetBlobLen(intset *is) { - return sizeof(intset) + intrev32ifbe(is->length)*intrev32ifbe(is->encoding); + return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding); } #ifdef REDIS_TEST @@ -304,7 +292,7 @@ size_t intsetBlobLen(intset *is) { #if 0 static void intsetRepr(intset *is) { for (uint32_t i = 0; i < intrev32ifbe(is->length); i++) { - printf("%lld\n", (uint64_t) _intsetGet(is, i)); + printf("%lld\n", (uint64_t)_intsetGet(is,i)); } printf("\n"); } @@ -321,48 +309,45 @@ static void ok(void) { static PORT_LONGLONG usec(void) { struct timeval tv; - gettimeofday(&tv, NULL); - return (((PORT_LONGLONG) tv.tv_sec) * 1000000) + tv.tv_usec; + gettimeofday(&tv,NULL); + return (((PORT_LONGLONG)tv.tv_sec)*1000000)+tv.tv_usec; } #define assert(_e) ((_e)?(void)0:(_assert(#_e,__FILE__,__LINE__),exit(1))) static void _assert(char *estr, char *file, int line) { printf("\n\n=== ASSERTION FAILED ===\n"); - printf("==> %s:%d '%s' is not true\n", file, line, estr); + printf("==> %s:%d '%s' is not true\n",file,line,estr); } static intset *createSet(int bits, int size) { - uint64_t mask = (1 << bits) - 1; + uint64_t mask = (1< 32) { value = (rand()*rand()) & mask; - } - else { + } else { value = rand() & mask; } - is = intsetAdd(is, value, NULL); + is = intsetAdd(is,value,NULL); } return is; } static void checkConsistency(intset *is) { - for (uint32_t i = 0; i < (intrev32ifbe(is->length) - 1); i++) { + for (uint32_t i = 0; i < (intrev32ifbe(is->length)-1); i++) { uint32_t encoding = intrev32ifbe(is->encoding); if (encoding == INTSET_ENC_INT16) { - int16_t *i16 = (int16_t*) is->contents; - assert(i16[i] < i16[i + 1]); - } - else if (encoding == INTSET_ENC_INT32) { - int32_t *i32 = (int32_t*) is->contents; - assert(i32[i] < i32[i + 1]); - } - else { - int64_t *i64 = (int64_t*) is->contents; - assert(i64[i] < i64[i + 1]); + int16_t *i16 = (int16_t*)is->contents; + assert(i16[i] < i16[i+1]); + } else if (encoding == INTSET_ENC_INT32) { + int32_t *i32 = (int32_t*)is->contents; + assert(i32[i] < i32[i+1]); + } else { + int64_t *i64 = (int64_t*)is->contents; + assert(i64[i] < i64[i+1]); } } } @@ -387,18 +372,18 @@ int intsetTest(int argc, char **argv) { assert(_intsetValueEncoding(-2147483649) == INTSET_ENC_INT64); assert(_intsetValueEncoding(+2147483648) == INTSET_ENC_INT64); assert(_intsetValueEncoding(-9223372036854775808ull) == - INTSET_ENC_INT64); + INTSET_ENC_INT64); assert(_intsetValueEncoding(+9223372036854775807ull) == - INTSET_ENC_INT64); + INTSET_ENC_INT64); ok(); } printf("Basic adding: "); { is = intsetNew(); - is = intsetAdd(is, 5, &success); assert(success); - is = intsetAdd(is, 6, &success); assert(success); - is = intsetAdd(is, 4, &success); assert(success); - is = intsetAdd(is, 4, &success); assert(!success); + is = intsetAdd(is,5,&success); assert(success); + is = intsetAdd(is,6,&success); assert(success); + is = intsetAdd(is,4,&success); assert(success); + is = intsetAdd(is,4,&success); assert(!success); ok(); } @@ -406,7 +391,7 @@ int intsetTest(int argc, char **argv) { uint32_t inserts = 0; is = intsetNew(); for (i = 0; i < 1024; i++) { - is = intsetAdd(is, rand() % 0x800, &success); + is = intsetAdd(is,rand()%0x800,&success); if (success) inserts++; } assert(intrev32ifbe(is->length) == inserts); @@ -416,63 +401,63 @@ int intsetTest(int argc, char **argv) { printf("Upgrade from int16 to int32: "); { is = intsetNew(); - is = intsetAdd(is, 32, NULL); + is = intsetAdd(is,32,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16); - is = intsetAdd(is, 65535, NULL); + is = intsetAdd(is,65535,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32); - assert(intsetFind(is, 32)); - assert(intsetFind(is, 65535)); + assert(intsetFind(is,32)); + assert(intsetFind(is,65535)); checkConsistency(is); is = intsetNew(); - is = intsetAdd(is, 32, NULL); + is = intsetAdd(is,32,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16); - is = intsetAdd(is, -65535, NULL); + is = intsetAdd(is,-65535,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32); - assert(intsetFind(is, 32)); - assert(intsetFind(is, -65535)); + assert(intsetFind(is,32)); + assert(intsetFind(is,-65535)); checkConsistency(is); ok(); } printf("Upgrade from int16 to int64: "); { is = intsetNew(); - is = intsetAdd(is, 32, NULL); + is = intsetAdd(is,32,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16); - is = intsetAdd(is, 4294967295, NULL); + is = intsetAdd(is,4294967295,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64); - assert(intsetFind(is, 32)); - assert(intsetFind(is, 4294967295)); + assert(intsetFind(is,32)); + assert(intsetFind(is,4294967295)); checkConsistency(is); is = intsetNew(); - is = intsetAdd(is, 32, NULL); + is = intsetAdd(is,32,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16); - is = intsetAdd(is, -4294967295, NULL); + is = intsetAdd(is,-4294967295,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64); - assert(intsetFind(is, 32)); - assert(intsetFind(is, -4294967295)); + assert(intsetFind(is,32)); + assert(intsetFind(is,-4294967295)); checkConsistency(is); ok(); } printf("Upgrade from int32 to int64: "); { is = intsetNew(); - is = intsetAdd(is, 65535, NULL); + is = intsetAdd(is,65535,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32); - is = intsetAdd(is, 4294967295, NULL); + is = intsetAdd(is,4294967295,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64); - assert(intsetFind(is, 65535)); - assert(intsetFind(is, 4294967295)); + assert(intsetFind(is,65535)); + assert(intsetFind(is,4294967295)); checkConsistency(is); is = intsetNew(); - is = intsetAdd(is, 65535, NULL); + is = intsetAdd(is,65535,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32); - is = intsetAdd(is, -4294967295, NULL); + is = intsetAdd(is,-4294967295,NULL); assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64); - assert(intsetFind(is, 65535)); - assert(intsetFind(is, -4294967295)); + assert(intsetFind(is,65535)); + assert(intsetFind(is,-4294967295)); checkConsistency(is); ok(); } @@ -481,13 +466,13 @@ int intsetTest(int argc, char **argv) { PORT_LONG num = 100000, size = 10000; int i, bits = 20; PORT_LONGLONG start; - is = createSet(bits, size); + is = createSet(bits,size); checkConsistency(is); start = usec(); - for (i = 0; i < num; i++) intsetSearch(is, rand() % ((1 << bits) - 1), NULL); + for (i = 0; i < num; i++) intsetSearch(is,rand() % ((1<samples[ts->idx].time = (int32_t)time(NULL); WIN_PORT_FIX /* cast (int32_t) */ ts->samples[ts->idx].latency = (int32_t)latency; WIN_PORT_FIX /* cast (int32_t) */ - + ts->idx++; if (ts->idx == LATENCY_TS_LEN) ts->idx = 0; } diff --git a/src/lzfP.h b/src/lzfP.h index c6d2e096..93c27b42 100644 --- a/src/lzfP.h +++ b/src/lzfP.h @@ -79,7 +79,11 @@ * Unconditionally aligning does not cost very much, so do it if unsure */ #ifndef STRICT_ALIGN -# define STRICT_ALIGN !(defined(__i386) || defined (__amd64)) +# if !(defined(__i386) || defined (__amd64)) +# define STRICT_ALIGN 1 +# else +# define STRICT_ALIGN 0 +# endif #endif /* diff --git a/src/memtest.c b/src/memtest.c index 022ca960..aebd84b6 100644 --- a/src/memtest.c +++ b/src/memtest.c @@ -111,7 +111,7 @@ void memtest_progress_step(size_t curr, size_t size, char c) { * ASAP big issues with the memory subsystem. */ int memtest_addressing(PORT_ULONG *l, size_t bytes, int interactive) { PORT_ULONG words = (PORT_ULONG)(bytes/sizeof(PORT_ULONG)); - PORT_ULONG j,*p; + PORT_ULONG j, *p; /* Fill */ p = l; diff --git a/src/module.c b/src/module.c index a8945fa0..4cdb6cf0 100644 --- a/src/module.c +++ b/src/module.c @@ -32,21 +32,21 @@ #ifndef _WIN32 #include #else -#include "Win32_Interop\dlfcn.h" -#include "Win32_Interop\Win32_PThread.h" +#include "Win32_Interop/dlfcn.h" +#include "Win32_Interop/Win32_PThread.h" #include "Win32_Interop/Win32_Error.h" #endif #define REDISMODULE_CORE 1 #include "redismodule.h" - /* -------------------------------------------------------------------------- - * Private data structures used by the modules system. Those are data - * structures that are never exposed to Redis Modules, if not as void - * pointers that have an API the module can call with them) - * -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- + * Private data structures used by the modules system. Those are data + * structures that are never exposed to Redis Modules, if not as void + * pointers that have an API the module can call with them) + * -------------------------------------------------------------------------- */ - /* This structure represents a module inside the system. */ +/* This structure represents a module inside the system. */ struct RedisModule { void *handle; /* Module dlopen() handle. */ char *name; /* Module name. */ @@ -126,7 +126,6 @@ struct RedisModuleCtx { }; typedef struct RedisModuleCtx RedisModuleCtx; -//#define REDISMODULE_CTX_INIT {(void*)(PORT_ULONG)&RM_GetApi, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, NULL, NULL, 0, NULL} #define REDISMODULE_CTX_INIT {(void*)(PORT_ULONG)&RM_GetApi, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, NULL, NULL, 0, NULL} #define REDISMODULE_CTX_MULTI_EMITTED (1<<0) #define REDISMODULE_CTX_AUTO_MEMORY (1<<1) @@ -164,7 +163,7 @@ typedef struct RedisModuleKey RedisModuleKey; /* Function pointer type of a function representing a command inside * a Redis module. */ -typedef int(*RedisModuleCmdFunc) (RedisModuleCtx *ctx, void **argv, int argc); +typedef int (*RedisModuleCmdFunc) (RedisModuleCtx *ctx, void **argv, int argc); /* This struct holds the information about a command registered by a module.*/ struct RedisModuleCommandProxy { @@ -179,9 +178,9 @@ typedef struct RedisModuleCommandProxy RedisModuleCommandProxy; #define REDISMODULE_REPLYFLAG_NESTED (1<<1) /* Nested reply object. No proto or struct free. */ - /* Reply of RM_Call() function. The function is filled in a lazy - * way depending on the function called on the reply structure. By default - * only the type, proto and protolen are filled. */ +/* Reply of RM_Call() function. The function is filled in a lazy + * way depending on the function called on the reply structure. By default + * only the type, proto and protolen are filled. */ typedef struct RedisModuleCallReply { RedisModuleCtx *ctx; int type; /* REDISMODULE_REPLY_... */ @@ -207,7 +206,7 @@ typedef struct RedisModuleBlockedClient { RedisModule *module; /* Module blocking the client. */ RedisModuleCmdFunc reply_callback; /* Reply callback on normal completion.*/ RedisModuleCmdFunc timeout_callback; /* Reply callback on timeout. */ - void(*free_privdata)(void *); /* privdata cleanup callback. */ + void (*free_privdata)(void *); /* privdata cleanup callback. */ void *privdata; /* Module private data that may be used by the reply or timeout callback. It is set via the RedisModule_UnblockClient() API. */ @@ -232,6 +231,7 @@ pthread_mutex_t moduleGIL; #endif /* Function pointer type for keyspace event notification subscriptions from modules. */ typedef int (*RedisModuleNotificationFunc) (RedisModuleCtx *ctx, int type, const char *event, RedisModuleString *key); + /* Keyspace notification subscriber information. * See RM_SubscribeToKeyspaceEvents() for more information. */ typedef struct RedisModuleKeyspaceSubscriber { @@ -269,10 +269,10 @@ static void zsetKeyReset(RedisModuleKey *key); * Heap allocation raw functions * -------------------------------------------------------------------------- */ - /* Use like malloc(). Memory allocated with this function is reported in - * Redis INFO memory, used for keys eviction according to maxmemory settings - * and in general is taken into account as memory allocated by Redis. - * You should avoid using malloc(). */ +/* Use like malloc(). Memory allocated with this function is reported in + * Redis INFO memory, used for keys eviction according to maxmemory settings + * and in general is taken into account as memory allocated by Redis. + * You should avoid using malloc(). */ void *RM_Alloc(size_t bytes) { return zmalloc(bytes); } @@ -287,7 +287,7 @@ void *RM_Calloc(size_t nmemb, size_t size) { /* Use like realloc() for memory obtained with RedisModule_Alloc(). */ void* RM_Realloc(void *ptr, size_t bytes) { - return zrealloc(ptr, bytes); + return zrealloc(ptr,bytes); } /* Use like free() for memory obtained by RedisModule_Alloc() and @@ -306,11 +306,11 @@ char *RM_Strdup(const char *str) { * Pool allocator * -------------------------------------------------------------------------- */ - /* Release the chain of blocks used for pool allocations. */ +/* Release the chain of blocks used for pool allocations. */ void poolAllocRelease(RedisModuleCtx *ctx) { RedisModulePoolAllocBlock *head = ctx->pa_head, *next; - while (head != NULL) { + while(head != NULL) { next = head->next; zfree(head); head = next; @@ -338,7 +338,7 @@ void *RM_PoolAlloc(RedisModuleCtx *ctx, size_t bytes) { /* Fix alignment. */ if (left >= bytes) { size_t alignment = REDISMODULE_POOL_ALLOC_ALIGN; - while (bytes < alignment && alignment / 2 >= bytes) alignment /= 2; + while (bytes < alignment && alignment/2 >= bytes) alignment /= 2; if (b->used % alignment) b->used += alignment - (b->used % alignment); left = (b->used > b->size) ? 0 : b->size - b->used; @@ -364,18 +364,18 @@ void *RM_PoolAlloc(RedisModuleCtx *ctx, size_t bytes) { * Helpers for modules API implementation * -------------------------------------------------------------------------- */ - /* Create an empty key of the specified type. 'kp' must point to a key object - * opened for writing where the .value member is set to NULL because the - * key was found to be non existing. - * - * On success REDISMODULE_OK is returned and the key is populated with - * the value of the specified type. The function fails and returns - * REDISMODULE_ERR if: - * - * 1) The key is not open for writing. - * 2) The key is not empty. - * 3) The specified type is unknown. - */ +/* Create an empty key of the specified type. 'kp' must point to a key object + * opened for writing where the .value member is set to NULL because the + * key was found to be non existing. + * + * On success REDISMODULE_OK is returned and the key is populated with + * the value of the specified type. The function fails and returns + * REDISMODULE_ERR if: + * + * 1) The key is not open for writing. + * 2) The key is not empty. + * 3) The specified type is unknown. + */ int moduleCreateEmptyKey(RedisModuleKey *key, int type) { robj *obj; @@ -383,11 +383,11 @@ int moduleCreateEmptyKey(RedisModuleKey *key, int type) { if (!(key->mode & REDISMODULE_WRITE) || key->value) return REDISMODULE_ERR; - switch (type) { + switch(type) { case REDISMODULE_KEYTYPE_LIST: obj = createQuicklistObject(); quicklistSetOptions(obj->ptr, server.list_max_ziplist_size, - server.list_compress_depth); + server.list_compress_depth); break; case REDISMODULE_KEYTYPE_ZSET: obj = createZsetZiplistObject(); @@ -397,7 +397,7 @@ int moduleCreateEmptyKey(RedisModuleKey *key, int type) { break; default: return REDISMODULE_ERR; } - dbAdd(key->db, key->key, obj); + dbAdd(key->db,key->key,obj); key->value = obj; return REDISMODULE_OK; } @@ -417,20 +417,19 @@ int moduleDelKeyIfEmpty(RedisModuleKey *key) { int isempty; robj *o = key->value; - switch (o->type) { + switch(o->type) { case OBJ_LIST: isempty = listTypeLength(o) == 0; break; case OBJ_SET: isempty = setTypeSize(o) == 0; break; case OBJ_ZSET: isempty = zsetLength(o) == 0; break; - case OBJ_HASH: isempty = hashTypeLength(o) == 0; break; + case OBJ_HASH : isempty = hashTypeLength(o) == 0; break; default: isempty = 0; } if (isempty) { - dbDelete(key->db, key->key); + dbDelete(key->db,key->key); key->value = NULL; return 1; - } - else { + } else { return 0; } } @@ -445,12 +444,12 @@ int moduleDelKeyIfEmpty(RedisModuleKey *key) { * defined in the main executable having the same names. * -------------------------------------------------------------------------- */ - /* Lookup the requested module API and store the function pointer into the - * target pointer. The function returns REDISMODULE_ERR if there is no such - * named API, otherwise REDISMODULE_OK. - * - * This function is not meant to be used by modules developer, it is only - * used implicitly by including redismodule.h. */ +/* Lookup the requested module API and store the function pointer into the + * target pointer. The function returns REDISMODULE_ERR if there is no such + * named API, otherwise REDISMODULE_OK. + * + * This function is not meant to be used by modules developer, it is only + * used implicitly by including redismodule.h. */ int RM_GetApi(const char *funcname, void **targetPtrPtr) { dictEntry *he = dictFind(server.moduleapi, funcname); if (!he) return REDISMODULE_ERR; @@ -486,9 +485,9 @@ void moduleHandlePropagationAfterCommandCallback(RedisModuleCtx *ctx) { * emits is always wrappered around MULTI/EXEC. */ if (ctx->flags & REDISMODULE_CTX_MULTI_EMITTED) { robj *propargv[1]; - propargv[0] = createStringObject("EXEC", 4); - alsoPropagate(server.execCommand, c->db->id, propargv, 1, - PROPAGATE_AOF | PROPAGATE_REPL); + propargv[0] = createStringObject("EXEC",4); + alsoPropagate(server.execCommand,c->db->id,propargv,1, + PROPAGATE_AOF|PROPAGATE_REPL); decrRefCount(propargv[0]); } } @@ -496,12 +495,12 @@ void moduleHandlePropagationAfterCommandCallback(RedisModuleCtx *ctx) { /* This Redis command binds the normal Redis command invocation with commands * exported by modules. */ void RedisModuleCommandDispatcher(client *c) { - RedisModuleCommandProxy *cp = (void*) (PORT_ULONG) c->cmd->getkeys_proc; + RedisModuleCommandProxy *cp = (void*) (PORT_ULONG)c->cmd->getkeys_proc; RedisModuleCtx ctx = REDISMODULE_CTX_INIT; ctx.module = cp->module; ctx.client = c; - cp->func(&ctx, (void**) c->argv, c->argc); + cp->func(&ctx,(void**)c->argv,c->argc); moduleHandlePropagationAfterCommandCallback(&ctx); moduleFreeContext(&ctx); } @@ -516,13 +515,13 @@ void RedisModuleCommandDispatcher(client *c) { * the context in a way that the command can recognize this is a special * "get keys" call by calling RedisModule_IsKeysPositionRequest(ctx). */ int *moduleGetCommandKeysViaAPI(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) { - RedisModuleCommandProxy *cp = (void*) (PORT_ULONG) cmd->getkeys_proc; + RedisModuleCommandProxy *cp = (void*) (PORT_ULONG)cmd->getkeys_proc; RedisModuleCtx ctx = REDISMODULE_CTX_INIT; ctx.module = cp->module; ctx.client = NULL; ctx.flags |= REDISMODULE_CTX_KEYS_POS_REQUEST; - cp->func(&ctx, (void**) argv, argc); + cp->func(&ctx,(void**)argv,argc); int *res = ctx.keys_pos; if (numkeys) *numkeys = ctx.keys_count; moduleFreeContext(&ctx); @@ -553,7 +552,7 @@ int RM_IsKeysPositionRequest(RedisModuleCtx *ctx) { void RM_KeyAtPos(RedisModuleCtx *ctx, int pos) { if (!(ctx->flags & REDISMODULE_CTX_KEYS_POS_REQUEST)) return; if (pos <= 0) return; - ctx->keys_pos = zrealloc(ctx->keys_pos, sizeof(int)*(ctx->keys_count + 1)); + ctx->keys_pos = zrealloc(ctx->keys_pos,sizeof(int)*(ctx->keys_count+1)); ctx->keys_pos[ctx->keys_count++] = pos; } @@ -564,25 +563,25 @@ void RM_KeyAtPos(RedisModuleCtx *ctx, int pos) { int commandFlagsFromString(char *s) { int count, j; int flags = 0; - sds *tokens = sdssplitlen(s, strlen(s), " ", 1, &count); + sds *tokens = sdssplitlen(s,strlen(s)," ",1,&count); for (j = 0; j < count; j++) { char *t = tokens[j]; - if (!strcasecmp(t, "write")) flags |= CMD_WRITE; - else if (!strcasecmp(t, "readonly")) flags |= CMD_READONLY; - else if (!strcasecmp(t, "admin")) flags |= CMD_ADMIN; - else if (!strcasecmp(t, "deny-oom")) flags |= CMD_DENYOOM; - else if (!strcasecmp(t, "deny-script")) flags |= CMD_NOSCRIPT; - else if (!strcasecmp(t, "allow-loading")) flags |= CMD_LOADING; - else if (!strcasecmp(t, "pubsub")) flags |= CMD_PUBSUB; - else if (!strcasecmp(t, "random")) flags |= CMD_RANDOM; - else if (!strcasecmp(t, "allow-stale")) flags |= CMD_STALE; - else if (!strcasecmp(t, "no-monitor")) flags |= CMD_SKIP_MONITOR; - else if (!strcasecmp(t, "fast")) flags |= CMD_FAST; - else if (!strcasecmp(t, "getkeys-api")) flags |= CMD_MODULE_GETKEYS; - else if (!strcasecmp(t, "no-cluster")) flags |= CMD_MODULE_NO_CLUSTER; + if (!strcasecmp(t,"write")) flags |= CMD_WRITE; + else if (!strcasecmp(t,"readonly")) flags |= CMD_READONLY; + else if (!strcasecmp(t,"admin")) flags |= CMD_ADMIN; + else if (!strcasecmp(t,"deny-oom")) flags |= CMD_DENYOOM; + else if (!strcasecmp(t,"deny-script")) flags |= CMD_NOSCRIPT; + else if (!strcasecmp(t,"allow-loading")) flags |= CMD_LOADING; + else if (!strcasecmp(t,"pubsub")) flags |= CMD_PUBSUB; + else if (!strcasecmp(t,"random")) flags |= CMD_RANDOM; + else if (!strcasecmp(t,"allow-stale")) flags |= CMD_STALE; + else if (!strcasecmp(t,"no-monitor")) flags |= CMD_SKIP_MONITOR; + else if (!strcasecmp(t,"fast")) flags |= CMD_FAST; + else if (!strcasecmp(t,"getkeys-api")) flags |= CMD_MODULE_GETKEYS; + else if (!strcasecmp(t,"no-cluster")) flags |= CMD_MODULE_NO_CLUSTER; else break; } - sdsfreesplitres(tokens, count); + sdsfreesplitres(tokens,count); if (j != count) return -1; /* Some token not processed correctly. */ return flags; } @@ -641,7 +640,7 @@ int commandFlagsFromString(char *s) { * other reason. */ int RM_CreateCommand(RedisModuleCtx *ctx, const char *name, RedisModuleCmdFunc cmdfunc, const char *strflags, int firstkey, int lastkey, int keystep) { - int flags = strflags ? commandFlagsFromString((char*) strflags) : 0; + int flags = strflags ? commandFlagsFromString((char*)strflags) : 0; if (flags == -1) return REDISMODULE_ERR; if ((flags & CMD_MODULE_NO_CLUSTER) && server.cluster_enabled) return REDISMODULE_ERR; @@ -671,14 +670,14 @@ int RM_CreateCommand(RedisModuleCtx *ctx, const char *name, RedisModuleCmdFunc c cp->rediscmd->proc = RedisModuleCommandDispatcher; cp->rediscmd->arity = -1; cp->rediscmd->flags = flags | CMD_MODULE; - cp->rediscmd->getkeys_proc = (redisGetKeysProc*) (PORT_ULONG) cp; + cp->rediscmd->getkeys_proc = (redisGetKeysProc*) (PORT_ULONG)cp; cp->rediscmd->firstkey = firstkey; cp->rediscmd->lastkey = lastkey; cp->rediscmd->keystep = keystep; cp->rediscmd->microseconds = 0; cp->rediscmd->calls = 0; - dictAdd(server.commands, sdsdup(cmdname), cp->rediscmd); - dictAdd(server.orig_commands, sdsdup(cmdname), cp->rediscmd); + dictAdd(server.commands,sdsdup(cmdname),cp->rediscmd); + dictAdd(server.orig_commands,sdsdup(cmdname),cp->rediscmd); return REDISMODULE_OK; } @@ -691,7 +690,7 @@ void RM_SetModuleAttribs(RedisModuleCtx *ctx, const char *name, int ver, int api if (ctx->module != NULL) return; module = zmalloc(sizeof(*module)); - module->name = sdsnew((char*) name); + module->name = sdsnew((char*)name); module->ver = ver; module->apiver = apiver; module->types = listCreate(); @@ -716,10 +715,10 @@ PORT_LONGLONG RM_Milliseconds(void) { * Automatic memory management for modules * -------------------------------------------------------------------------- */ - /* Enable automatic memory management. See API.md for more information. - * - * The function must be called as the first function of a command implementation - * that wants to use automatic memory. */ +/* Enable automatic memory management. See API.md for more information. + * + * The function must be called as the first function of a command implementation + * that wants to use automatic memory. */ void RM_AutoMemory(RedisModuleCtx *ctx) { ctx->flags |= REDISMODULE_CTX_AUTO_MEMORY; } @@ -730,7 +729,7 @@ void autoMemoryAdd(RedisModuleCtx *ctx, int type, void *ptr) { if (ctx->amqueue_used == ctx->amqueue_len) { ctx->amqueue_len *= 2; if (ctx->amqueue_len < 16) ctx->amqueue_len = 16; - ctx->amqueue = zrealloc(ctx->amqueue, sizeof(struct AutoMemEntry)*ctx->amqueue_len); + ctx->amqueue = zrealloc(ctx->amqueue,sizeof(struct AutoMemEntry)*ctx->amqueue_len); } ctx->amqueue[ctx->amqueue_used].type = type; ctx->amqueue[ctx->amqueue_used].ptr = ptr; @@ -745,7 +744,7 @@ void autoMemoryAdd(RedisModuleCtx *ctx, int type, void *ptr) { int autoMemoryFreed(RedisModuleCtx *ctx, int type, void *ptr) { if (!(ctx->flags & REDISMODULE_CTX_AUTO_MEMORY)) return 0; - int count = (ctx->amqueue_used + 1) / 2; + int count = (ctx->amqueue_used+1)/2; for (int j = 0; j < count; j++) { for (int side = 0; side < 2; side++) { /* For side = 0 check right side of the array, for @@ -758,8 +757,8 @@ int autoMemoryFreed(RedisModuleCtx *ctx, int type, void *ptr) { /* Switch the freed element and the last element, to avoid growing * the queue unnecessarily if we allocate/free in a loop */ - if (i != ctx->amqueue_used - 1) { - ctx->amqueue[i] = ctx->amqueue[ctx->amqueue_used - 1]; + if (i != ctx->amqueue_used-1) { + ctx->amqueue[i] = ctx->amqueue[ctx->amqueue_used-1]; } /* Reduce the size of the queue because we either moved the top @@ -782,7 +781,7 @@ void autoMemoryCollect(RedisModuleCtx *ctx) { int j; for (j = 0; j < ctx->amqueue_used; j++) { void *ptr = ctx->amqueue[j].ptr; - switch (ctx->amqueue[j].type) { + switch(ctx->amqueue[j].type) { case REDISMODULE_AM_STRING: decrRefCount(ptr); break; case REDISMODULE_AM_REPLY: RM_FreeCallReply(ptr); break; case REDISMODULE_AM_KEY: RM_CloseKey(ptr); break; @@ -799,17 +798,18 @@ void autoMemoryCollect(RedisModuleCtx *ctx) { * String objects APIs * -------------------------------------------------------------------------- */ - /* Create a new module string object. The returned string must be freed - * with RedisModule_FreeString(), unless automatic memory is enabled. - * - * The string is created by copying the `len` bytes starting - * at `ptr`. No reference is retained to the passed buffer. */ +/* Create a new module string object. The returned string must be freed + * with RedisModule_FreeString(), unless automatic memory is enabled. + * + * The string is created by copying the `len` bytes starting + * at `ptr`. No reference is retained to the passed buffer. */ RedisModuleString *RM_CreateString(RedisModuleCtx *ctx, const char *ptr, size_t len) { - RedisModuleString *o = createStringObject(ptr, len); - autoMemoryAdd(ctx, REDISMODULE_AM_STRING, o); + RedisModuleString *o = createStringObject(ptr,len); + autoMemoryAdd(ctx,REDISMODULE_AM_STRING,o); return o; } + /* Create a new module string object from a printf format and arguments. * The returned string must be freed with RedisModule_FreeString(), unless * automatic memory is enabled. @@ -824,21 +824,21 @@ RedisModuleString *RM_CreateStringPrintf(RedisModuleCtx *ctx, const char *fmt, . va_end(ap); RedisModuleString *o = createObject(OBJ_STRING, s); - autoMemoryAdd(ctx, REDISMODULE_AM_STRING, o); + autoMemoryAdd(ctx,REDISMODULE_AM_STRING,o); return o; } -/* Like RedisModule_CreateString(), but creates a string starting from a long long +/* Like RedisModule_CreatString(), but creates a string starting from a long long * integer instead of taking a buffer and its length. * * The returned string must be released with RedisModule_FreeString() or by * enabling automatic memory management. */ RedisModuleString *RM_CreateStringFromLongLong(RedisModuleCtx *ctx, PORT_LONGLONG ll) { char buf[LONG_STR_SIZE]; - size_t len = ll2string(buf, sizeof(buf), ll); - return RM_CreateString(ctx, buf, len); + size_t len = ll2string(buf,sizeof(buf),ll); + return RM_CreateString(ctx,buf,len); } /* Like RedisModule_CreatString(), but creates a string starting from another @@ -848,7 +848,7 @@ RedisModuleString *RM_CreateStringFromLongLong(RedisModuleCtx *ctx, PORT_LONGLON * enabling automatic memory management. */ RedisModuleString *RM_CreateStringFromString(RedisModuleCtx *ctx, const RedisModuleString *str) { RedisModuleString *o = dupStringObject(str); - autoMemoryAdd(ctx, REDISMODULE_AM_STRING, o); + autoMemoryAdd(ctx,REDISMODULE_AM_STRING,o); return o; } @@ -860,7 +860,7 @@ RedisModuleString *RM_CreateStringFromString(RedisModuleCtx *ctx, const RedisMod * from the pool of string to release at the end. */ void RM_FreeString(RedisModuleCtx *ctx, RedisModuleString *str) { decrRefCount(str); - autoMemoryFreed(ctx, REDISMODULE_AM_STRING, str); + autoMemoryFreed(ctx,REDISMODULE_AM_STRING,str); } /* Every call to this function, will make the string 'str' requiring @@ -886,7 +886,7 @@ void RM_FreeString(RedisModuleCtx *ctx, RedisModuleString *str) { * into a string that lives after the callback function returns, if * no FreeString() call is performed. */ void RM_RetainString(RedisModuleCtx *ctx, RedisModuleString *str) { - if (!autoMemoryFreed(ctx, REDISMODULE_AM_STRING, str)) { + if (!autoMemoryFreed(ctx,REDISMODULE_AM_STRING,str)) { /* Increment the string reference counting only if we can't * just remove the object from the list of objects that should * be reclaimed. Why we do that, instead of just incrementing @@ -917,20 +917,20 @@ const char *RM_StringPtrLen(const RedisModuleString *str, size_t *len) { * Higher level string operations * ------------------------------------------------------------------------- */ - /* Convert the string into a PORT_LONGLONG integer, storing it at `*ll`. - * Returns REDISMODULE_OK on success. If the string can't be parsed - * as a valid, strict PORT_LONGLONG (no spaces before/after), REDISMODULE_ERR - * is returned. */ +/* Convert the string into a PORT_LONGLONG integer, storing it at `*ll`. + * Returns REDISMODULE_OK on success. If the string can't be parsed + * as a valid, strict PORT_LONGLONG (no spaces before/after), REDISMODULE_ERR + * is returned. */ int RM_StringToLongLong(const RedisModuleString *str, PORT_LONGLONG *ll) { - return string2ll(str->ptr, sdslen(str->ptr), ll) ? REDISMODULE_OK : - REDISMODULE_ERR; + return string2ll(str->ptr,sdslen(str->ptr),ll) ? REDISMODULE_OK : + REDISMODULE_ERR; } /* Convert the string into a double, storing it at `*d`. * Returns REDISMODULE_OK on success or REDISMODULE_ERR if the string is * not a valid string representation of a double value. */ int RM_StringToDouble(const RedisModuleString *str, double *d) { - int retval = getDoubleFromObject(str, d); + int retval = getDoubleFromObject(str,d); return (retval == C_OK) ? REDISMODULE_OK : REDISMODULE_ERR; } @@ -938,7 +938,7 @@ int RM_StringToDouble(const RedisModuleString *str, double *d) { * a < b, a == b, a > b. Strings are compared byte by byte as two * binary blobs without any encoding care / collation attempt. */ int RM_StringCompare(RedisModuleString *a, RedisModuleString *b) { - return compareStringObjects(a, b); + return compareStringObjects(a,b); } /* Return the (possibly modified in encoding) input 'str' object if @@ -954,12 +954,11 @@ RedisModuleString *moduleAssertUnsharedString(RedisModuleString *str) { if (str->encoding == OBJ_ENCODING_EMBSTR) { /* Note: here we "leak" the additional allocation that was * used in order to store the embedded string in the object. */ - str->ptr = sdsnewlen(str->ptr, sdslen(str->ptr)); + str->ptr = sdsnewlen(str->ptr,sdslen(str->ptr)); str->encoding = OBJ_ENCODING_RAW; - } - else if (str->encoding == OBJ_ENCODING_INT) { + } else if (str->encoding == OBJ_ENCODING_INT) { /* Convert the string from integer to raw encoding. */ - str->ptr = sdsfromlonglong((PORT_LONG) str->ptr); + str->ptr = sdsfromlonglong((PORT_LONG)str->ptr); str->encoding = OBJ_ENCODING_RAW; } return str; @@ -972,7 +971,7 @@ int RM_StringAppendBuffer(RedisModuleCtx *ctx, RedisModuleString *str, const cha UNUSED(ctx); str = moduleAssertUnsharedString(str); if (str == NULL) return REDISMODULE_ERR; - str->ptr = sdscatlen(str->ptr, buf, len); + str->ptr = sdscatlen(str->ptr,buf,len); return REDISMODULE_OK; } @@ -986,17 +985,17 @@ int RM_StringAppendBuffer(RedisModuleCtx *ctx, RedisModuleString *str, const cha * return RM_ReplyWithLongLong(ctx,mycount); * -------------------------------------------------------------------------- */ - /* Send an error about the number of arguments given to the command, - * citing the command name in the error message. - * - * Example: - * - * if (argc != 3) return RedisModule_WrongArity(ctx); - */ +/* Send an error about the number of arguments given to the command, + * citing the command name in the error message. + * + * Example: + * + * if (argc != 3) return RedisModule_WrongArity(ctx); + */ int RM_WrongArity(RedisModuleCtx *ctx) { addReplyErrorFormat(ctx->client, "wrong number of arguments for '%s' command", - (char*) ctx->client->argv[0]->ptr); + (char*)ctx->client->argv[0]->ptr); return REDISMODULE_OK; } @@ -1021,12 +1020,12 @@ client *moduleGetReplyClient(RedisModuleCtx *ctx) { return NULL; } -/* Send an integer reply to the client, with the specified PORT_LONGLONG value. +/* Send an integer reply to the client, with the specified long long value. * The function always returns REDISMODULE_OK. */ int RM_ReplyWithLongLong(RedisModuleCtx *ctx, PORT_LONGLONG ll) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - addReplyLongLong(c, ll); + addReplyLongLong(c,ll); return REDISMODULE_OK; } @@ -1036,10 +1035,10 @@ int RM_ReplyWithLongLong(RedisModuleCtx *ctx, PORT_LONGLONG ll) { int replyWithStatus(RedisModuleCtx *ctx, const char *msg, char *prefix) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - sds strmsg = sdsnewlen(prefix, 1); - strmsg = sdscat(strmsg, msg); - strmsg = sdscatlen(strmsg, "\r\n", 2); - addReplySds(c, strmsg); + sds strmsg = sdsnewlen(prefix,1); + strmsg = sdscat(strmsg,msg); + strmsg = sdscatlen(strmsg,"\r\n",2); + addReplySds(c,strmsg); return REDISMODULE_OK; } @@ -1058,7 +1057,7 @@ int replyWithStatus(RedisModuleCtx *ctx, const char *msg, char *prefix) { * The function always returns REDISMODULE_OK. */ int RM_ReplyWithError(RedisModuleCtx *ctx, const char *err) { - return replyWithStatus(ctx, err, "-"); + return replyWithStatus(ctx,err,"-"); } /* Reply with a simple string (+... \r\n in RESP protocol). This replies @@ -1067,7 +1066,7 @@ int RM_ReplyWithError(RedisModuleCtx *ctx, const char *err) { * * The function always returns REDISMODULE_OK. */ int RM_ReplyWithSimpleString(RedisModuleCtx *ctx, const char *msg) { - return replyWithStatus(ctx, msg, "+"); + return replyWithStatus(ctx,msg,"+"); } /* Reply with an array type of 'len' elements. However 'len' other calls @@ -1085,14 +1084,13 @@ int RM_ReplyWithArray(RedisModuleCtx *ctx, PORT_LONG len) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; if (len == REDISMODULE_POSTPONED_ARRAY_LEN) { - ctx->postponed_arrays = zrealloc(ctx->postponed_arrays, sizeof(void*)* - (ctx->postponed_arrays_count + 1)); + ctx->postponed_arrays = zrealloc(ctx->postponed_arrays,sizeof(void*)* + (ctx->postponed_arrays_count+1)); ctx->postponed_arrays[ctx->postponed_arrays_count] = addDeferredMultiBulkLength(c); ctx->postponed_arrays_count++; - } - else { - addReplyMultiBulkLen(c, len); + } else { + addReplyMultiBulkLen(c,len); } return REDISMODULE_OK; } @@ -1132,12 +1130,12 @@ void RM_ReplySetArrayLength(RedisModuleCtx *ctx, PORT_LONG len) { "RedisModule_ReplySetArrayLength() called without previous " "RedisModule_ReplyWithArray(ctx,REDISMODULE_POSTPONED_ARRAY_LEN) " "call.", ctx->module->name); - return; + return; } ctx->postponed_arrays_count--; setDeferredMultiBulkLength(c, - ctx->postponed_arrays[ctx->postponed_arrays_count], - len); + ctx->postponed_arrays[ctx->postponed_arrays_count], + len); if (ctx->postponed_arrays_count == 0) { zfree(ctx->postponed_arrays); ctx->postponed_arrays = NULL; @@ -1150,7 +1148,7 @@ void RM_ReplySetArrayLength(RedisModuleCtx *ctx, PORT_LONG len) { int RM_ReplyWithStringBuffer(RedisModuleCtx *ctx, const char *buf, size_t len) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - addReplyBulkCBuffer(c, (char*) buf, len); + addReplyBulkCBuffer(c,(char*)buf,len); return REDISMODULE_OK; } @@ -1160,7 +1158,7 @@ int RM_ReplyWithStringBuffer(RedisModuleCtx *ctx, const char *buf, size_t len) { int RM_ReplyWithString(RedisModuleCtx *ctx, RedisModuleString *str) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - addReplyBulk(c, str); + addReplyBulk(c,str); return REDISMODULE_OK; } @@ -1171,7 +1169,7 @@ int RM_ReplyWithString(RedisModuleCtx *ctx, RedisModuleString *str) { int RM_ReplyWithNull(RedisModuleCtx *ctx) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - addReply(c, shared.nullbulk); + addReply(c,shared.nullbulk); return REDISMODULE_OK; } @@ -1185,7 +1183,7 @@ int RM_ReplyWithCallReply(RedisModuleCtx *ctx, RedisModuleCallReply *reply) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; sds proto = sdsnewlen(reply->proto, reply->protolen); - addReplySds(c, proto); + addReplySds(c,proto); return REDISMODULE_OK; } @@ -1198,7 +1196,7 @@ int RM_ReplyWithCallReply(RedisModuleCtx *ctx, RedisModuleCallReply *reply) { int RM_ReplyWithDouble(RedisModuleCtx *ctx, double d) { client *c = moduleGetReplyClient(ctx); if (c == NULL) return REDISMODULE_OK; - addReplyDouble(c, d); + addReplyDouble(c,d); return REDISMODULE_OK; } @@ -1206,9 +1204,9 @@ int RM_ReplyWithDouble(RedisModuleCtx *ctx, double d) { * Commands replication API * -------------------------------------------------------------------------- */ - /* Helper function to replicate MULTI the first time we replicate something - * in the context of a command execution. EXEC will be handled by the - * RedisModuleCommandDispatcher() function. */ +/* Helper function to replicate MULTI the first time we replicate something + * in the context of a command execution. EXEC will be handled by the + * RedisModuleCommandDispatcher() function. */ void moduleReplicateMultiIfNeeded(RedisModuleCtx *ctx) { /* Skip this if client explicitly wrap the command with MULTI, or if * the module command was called by a script. */ @@ -1248,19 +1246,19 @@ int RM_Replicate(RedisModuleCtx *ctx, const char *cmdname, const char *fmt, ...) int argc = 0, flags = 0, j; va_list ap; - cmd = lookupCommandByCString((char*) cmdname); + cmd = lookupCommandByCString((char*)cmdname); if (!cmd) return REDISMODULE_ERR; /* Create the client and dispatch the command. */ va_start(ap, fmt); - argv = moduleCreateArgvFromUserFormat(cmdname, fmt, &argc, &flags, ap); + argv = moduleCreateArgvFromUserFormat(cmdname,fmt,&argc,&flags,ap); va_end(ap); if (argv == NULL) return REDISMODULE_ERR; /* Replicate! */ moduleReplicateMultiIfNeeded(ctx); - alsoPropagate(cmd, ctx->client->db->id, argv, argc, - PROPAGATE_AOF | PROPAGATE_REPL); + alsoPropagate(cmd,ctx->client->db->id,argv,argc, + PROPAGATE_AOF|PROPAGATE_REPL); /* Release the argv. */ for (j = 0; j < argc; j++) decrRefCount(argv[j]); @@ -1292,17 +1290,17 @@ int RM_ReplicateVerbatim(RedisModuleCtx *ctx) { * DB and Key APIs -- Generic API * -------------------------------------------------------------------------- */ - /* Return the ID of the current client calling the currently active module - * command. The returned ID has a few guarantees: - * - * 1. The ID is different for each different client, so if the same client - * executes a module command multiple times, it can be recognized as - * having the same ID, otherwise the ID will be different. - * 2. The ID increases monotonically. Clients connecting to the server later - * are guaranteed to get IDs greater than any past ID previously seen. - * - * Valid IDs are from 1 to 2^64-1. If 0 is returned it means there is no way - * to fetch the ID in the context the function was currently called. */ +/* Return the ID of the current client calling the currently active module + * command. The returned ID has a few guarantees: + * + * 1. The ID is different for each different client, so if the same client + * executes a module command multiple times, it can be recognized as + * having the same ID, otherwise the ID will be different. + * 2. The ID increases monotonically. Clients connecting to the server later + * are guaranteed to get IDs greater than any past ID previously seen. + * + * Valid IDs are from 1 to 2^64-1. If 0 is returned it means there is no way + * to fetch the ID in the context the function was currently called. */ PORT_ULONGLONG RM_GetClientId(RedisModuleCtx *ctx) { if (ctx->client == NULL) return 0; return ctx->client->id; @@ -1392,7 +1390,7 @@ int RM_GetContextFlags(RedisModuleCtx *ctx) { * returns back to the original one, it should call RedisModule_GetSelectedDb() * before in order to restore the old DB number before returning. */ int RM_SelectDb(RedisModuleCtx *ctx, int newid) { - int retval = selectDb(ctx->client, newid); + int retval = selectDb(ctx->client,newid); return (retval == C_OK) ? REDISMODULE_OK : REDISMODULE_ERR; } @@ -1415,10 +1413,9 @@ void *RM_OpenKey(RedisModuleCtx *ctx, robj *keyname, int mode) { robj *value; if (mode & REDISMODULE_WRITE) { - value = lookupKeyWrite(ctx->client->db, keyname); - } - else { - value = lookupKeyRead(ctx->client->db, keyname); + value = lookupKeyWrite(ctx->client->db,keyname); + } else { + value = lookupKeyRead(ctx->client->db,keyname); if (value == NULL) { return NULL; } @@ -1434,28 +1431,28 @@ void *RM_OpenKey(RedisModuleCtx *ctx, robj *keyname, int mode) { kp->iter = NULL; kp->mode = mode; zsetKeyReset(kp); - autoMemoryAdd(ctx, REDISMODULE_AM_KEY, kp); - return (void*) kp; + autoMemoryAdd(ctx,REDISMODULE_AM_KEY,kp); + return (void*)kp; } /* Close a key handle. */ void RM_CloseKey(RedisModuleKey *key) { if (key == NULL) return; - if (key->mode & REDISMODULE_WRITE) signalModifiedKey(key->db, key->key); + if (key->mode & REDISMODULE_WRITE) signalModifiedKey(key->db,key->key); /* TODO: if (key->iter) RM_KeyIteratorStop(kp); */ RM_ZsetRangeStop(key); decrRefCount(key->key); - autoMemoryFreed(key->ctx, REDISMODULE_AM_KEY, key); + autoMemoryFreed(key->ctx,REDISMODULE_AM_KEY,key); zfree(key); } /* Return the type of the key. If the key pointer is NULL then * REDISMODULE_KEYTYPE_EMPTY is returned. */ int RM_KeyType(RedisModuleKey *key) { - if (key == NULL || key->value == NULL) return REDISMODULE_KEYTYPE_EMPTY; + if (key == NULL || key->value == NULL) return REDISMODULE_KEYTYPE_EMPTY; /* We map between defines so that we are free to change the internal * defines as desired. */ - switch (key->value->type) { + switch(key->value->type) { case OBJ_STRING: return REDISMODULE_KEYTYPE_STRING; case OBJ_LIST: return REDISMODULE_KEYTYPE_LIST; case OBJ_SET: return REDISMODULE_KEYTYPE_SET; @@ -1473,7 +1470,7 @@ int RM_KeyType(RedisModuleKey *key) { * If the key pointer is NULL or the key is empty, zero is returned. */ size_t RM_ValueLength(RedisModuleKey *key) { if (key == NULL || key->value == NULL) return 0; - switch (key->value->type) { + switch(key->value->type) { case OBJ_STRING: return stringObjectLen(key->value); case OBJ_LIST: return listTypeLength(key->value); case OBJ_SET: return setTypeSize(key->value); @@ -1490,7 +1487,7 @@ size_t RM_ValueLength(RedisModuleKey *key) { int RM_DeleteKey(RedisModuleKey *key) { if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value) { - dbDelete(key->db, key->key); + dbDelete(key->db,key->key); key->value = NULL; } return REDISMODULE_OK; @@ -1514,7 +1511,7 @@ int RM_UnlinkKey(RedisModuleKey *key) { * If no TTL is associated with the key or if the key is empty, * REDISMODULE_NO_EXPIRE is returned. */ mstime_t RM_GetExpire(RedisModuleKey *key) { - mstime_t expire = getExpire(key->db, key->key); + mstime_t expire = getExpire(key->db,key->key); if (expire == -1 || key->value == NULL) return -1; expire -= mstime(); return expire >= 0 ? expire : 0; @@ -1534,10 +1531,9 @@ int RM_SetExpire(RedisModuleKey *key, mstime_t expire) { return REDISMODULE_ERR; if (expire != REDISMODULE_NO_EXPIRE) { expire += mstime(); - setExpire(key->ctx->client, key->db, key->key, expire); - } - else { - removeExpire(key->db, key->key); + setExpire(key->ctx->client,key->db,key->key,expire); + } else { + removeExpire(key->db,key->key); } return REDISMODULE_OK; } @@ -1546,14 +1542,14 @@ int RM_SetExpire(RedisModuleKey *key, mstime_t expire) { * Key API for String type * -------------------------------------------------------------------------- */ - /* If the key is open for writing, set the specified string 'str' as the - * value of the key, deleting the old value if any. - * On success REDISMODULE_OK is returned. If the key is not open for - * writing or there is an active iterator, REDISMODULE_ERR is returned. */ +/* If the key is open for writing, set the specified string 'str' as the + * value of the key, deleting the old value if any. + * On success REDISMODULE_OK is returned. If the key is not open for + * writing or there is an active iterator, REDISMODULE_ERR is returned. */ int RM_StringSet(RedisModuleKey *key, RedisModuleString *str) { if (!(key->mode & REDISMODULE_WRITE) || key->iter) return REDISMODULE_ERR; RM_DeleteKey(key); - setKey(key->db, key->key, str); + setKey(key->db,key->key,str); key->value = str; return REDISMODULE_OK; } @@ -1624,7 +1620,7 @@ char *RM_StringDMA(RedisModuleKey *key, size_t *len, int mode) { int RM_StringTruncate(RedisModuleKey *key, size_t newlen) { if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value && key->value->type != OBJ_STRING) return REDISMODULE_ERR; - if (newlen > 512 * 1024 * 1024) return REDISMODULE_ERR; + if (newlen > 512*1024*1024) return REDISMODULE_ERR; /* Empty key and new len set to 0. Just return REDISMODULE_OK without * doing anything. */ @@ -1632,20 +1628,18 @@ int RM_StringTruncate(RedisModuleKey *key, size_t newlen) { if (key->value == NULL) { /* Empty key: create it with the new size. */ - robj *o = createObject(OBJ_STRING, sdsnewlen(NULL, newlen)); - setKey(key->db, key->key, o); + robj *o = createObject(OBJ_STRING,sdsnewlen(NULL, newlen)); + setKey(key->db,key->key,o); key->value = o; decrRefCount(o); - } - else { + } else { /* Unshare and resize. */ key->value = dbUnshareStringValue(key->db, key->key, key->value); size_t curlen = sdslen(key->value->ptr); if (newlen > curlen) { - key->value->ptr = sdsgrowzero(key->value->ptr, newlen); - } - else if (newlen < curlen) { - sdsrange(key->value->ptr, 0, newlen - 1); + key->value->ptr = sdsgrowzero(key->value->ptr,newlen); + } else if (newlen < curlen) { + sdsrange(key->value->ptr,0,newlen-1); /* If the string is too wasteful, reallocate it. */ if (sdslen(key->value->ptr) < sdsavail(key->value->ptr)) key->value->ptr = sdsRemoveFreeSpace(key->value->ptr); @@ -1658,14 +1652,14 @@ int RM_StringTruncate(RedisModuleKey *key, size_t newlen) { * Key API for List type * -------------------------------------------------------------------------- */ - /* Push an element into a list, on head or tail depending on 'where' argumnet. - * If the key pointer is about an empty key opened for writing, the key - * is created. On error (key opened for read-only operations or of the wrong - * type) REDISMODULE_ERR is returned, otherwise REDISMODULE_OK is returned. */ +/* Push an element into a list, on head or tail depending on 'where' argumnet. + * If the key pointer is about an empty key opened for writing, the key + * is created. On error (key opened for read-only operations or of the wrong + * type) REDISMODULE_ERR is returned, otherwise REDISMODULE_OK is returned. */ int RM_ListPush(RedisModuleKey *key, int where, RedisModuleString *ele) { if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value && key->value->type != OBJ_LIST) return REDISMODULE_ERR; - if (key->value == NULL) moduleCreateEmptyKey(key, REDISMODULE_KEYTYPE_LIST); + if (key->value == NULL) moduleCreateEmptyKey(key,REDISMODULE_KEYTYPE_LIST); listTypePush(key->value, ele, (where == REDISMODULE_LIST_HEAD) ? QUICKLIST_HEAD : QUICKLIST_TAIL); return REDISMODULE_OK; @@ -1687,7 +1681,7 @@ RedisModuleString *RM_ListPop(RedisModuleKey *key, int where) { robj *decoded = getDecodedObject(ele); decrRefCount(ele); moduleDelKeyIfEmpty(key); - autoMemoryAdd(key->ctx, REDISMODULE_AM_STRING, decoded); + autoMemoryAdd(key->ctx,REDISMODULE_AM_STRING,decoded); return decoded; } @@ -1695,8 +1689,8 @@ RedisModuleString *RM_ListPop(RedisModuleKey *key, int where) { * Key API for Sorted Set type * -------------------------------------------------------------------------- */ - /* Conversion from/to public flags of the Modules API and our private flags, - * so that we have everything decoupled. */ +/* Conversion from/to public flags of the Modules API and our private flags, + * so that we have everything decoupled. */ int RM_ZsetAddFlagsToCoreFlags(int flags) { int retflags = 0; if (flags & REDISMODULE_ZADD_XX) retflags |= ZADD_XX; @@ -1745,9 +1739,9 @@ int RM_ZsetAdd(RedisModuleKey *key, double score, RedisModuleString *ele, int *f int flags = 0; if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value && key->value->type != OBJ_ZSET) return REDISMODULE_ERR; - if (key->value == NULL) moduleCreateEmptyKey(key, REDISMODULE_KEYTYPE_ZSET); + if (key->value == NULL) moduleCreateEmptyKey(key,REDISMODULE_KEYTYPE_ZSET); if (flagsptr) flags = RM_ZsetAddFlagsToCoreFlags(*flagsptr); - if (zsetAdd(key->value, score, ele->ptr, &flags, NULL) == 0) { + if (zsetAdd(key->value,score,ele->ptr,&flags,NULL) == 0) { if (flagsptr) *flagsptr = 0; return REDISMODULE_ERR; } @@ -1772,10 +1766,10 @@ int RM_ZsetIncrby(RedisModuleKey *key, double score, RedisModuleString *ele, int int flags = 0; if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value && key->value->type != OBJ_ZSET) return REDISMODULE_ERR; - if (key->value == NULL) moduleCreateEmptyKey(key, REDISMODULE_KEYTYPE_ZSET); + if (key->value == NULL) moduleCreateEmptyKey(key,REDISMODULE_KEYTYPE_ZSET); if (flagsptr) flags = RM_ZsetAddFlagsToCoreFlags(*flagsptr); flags |= ZADD_INCR; - if (zsetAdd(key->value, score, ele->ptr, &flags, newscore) == 0) { + if (zsetAdd(key->value,score,ele->ptr,&flags,newscore) == 0) { if (flagsptr) *flagsptr = 0; return REDISMODULE_ERR; } @@ -1809,10 +1803,9 @@ int RM_ZsetIncrby(RedisModuleKey *key, double score, RedisModuleString *ele, int int RM_ZsetRem(RedisModuleKey *key, RedisModuleString *ele, int *deleted) { if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR; if (key->value && key->value->type != OBJ_ZSET) return REDISMODULE_ERR; - if (key->value != NULL && zsetDel(key->value, ele->ptr)) { + if (key->value != NULL && zsetDel(key->value,ele->ptr)) { if (deleted) *deleted = 1; - } - else { + } else { if (deleted) *deleted = 0; } return REDISMODULE_OK; @@ -1829,7 +1822,7 @@ int RM_ZsetRem(RedisModuleKey *key, RedisModuleString *ele, int *deleted) { int RM_ZsetScore(RedisModuleKey *key, RedisModuleString *ele, double *score) { if (key->value == NULL) return REDISMODULE_ERR; if (key->value->type != OBJ_ZSET) return REDISMODULE_ERR; - if (zsetScore(key->value, ele->ptr, score) == C_ERR) return REDISMODULE_ERR; + if (zsetScore(key->value,ele->ptr,score) == C_ERR) return REDISMODULE_ERR; return REDISMODULE_OK; } @@ -1881,16 +1874,14 @@ int zsetInitScoreRange(RedisModuleKey *key, double min, double max, int minex, i zrs->maxex = maxex; if (key->value->encoding == OBJ_ENCODING_ZIPLIST) { - key->zcurrent = first ? zzlFirstInRange(key->value->ptr, zrs) : - zzlLastInRange(key->value->ptr, zrs); - } - else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { + key->zcurrent = first ? zzlFirstInRange(key->value->ptr,zrs) : + zzlLastInRange(key->value->ptr,zrs); + } else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { zset *zs = key->value->ptr; zskiplist *zsl = zs->zsl; - key->zcurrent = first ? zslFirstInRange(zsl, zrs) : - zslLastInRange(zsl, zrs); - } - else { + key->zcurrent = first ? zslFirstInRange(zsl,zrs) : + zslLastInRange(zsl,zrs); + } else { serverPanic("Unsupported zset encoding"); } if (key->zcurrent == NULL) key->zer = 1; @@ -1913,13 +1904,13 @@ int zsetInitScoreRange(RedisModuleKey *key, double min, double max, int minex, i * where the min and max value are exclusive (not included) instead of * inclusive. */ int RM_ZsetFirstInScoreRange(RedisModuleKey *key, double min, double max, int minex, int maxex) { - return zsetInitScoreRange(key, min, max, minex, maxex, 1); + return zsetInitScoreRange(key,min,max,minex,maxex,1); } /* Exactly like RedisModule_ZsetFirstInScoreRange() but the last element of * the range is selected for the start of the iteration instead. */ int RM_ZsetLastInScoreRange(RedisModuleKey *key, double min, double max, int minex, int maxex) { - return zsetInitScoreRange(key, min, max, minex, maxex, 0); + return zsetInitScoreRange(key,min,max,minex,maxex,0); } /* Helper function for RM_ZsetFirstInLexRange() and RM_ZsetLastInLexRange(). @@ -1947,16 +1938,14 @@ int zsetInitLexRange(RedisModuleKey *key, RedisModuleString *min, RedisModuleStr key->ztype = REDISMODULE_ZSET_RANGE_LEX; if (key->value->encoding == OBJ_ENCODING_ZIPLIST) { - key->zcurrent = first ? zzlFirstInLexRange(key->value->ptr, zlrs) : - zzlLastInLexRange(key->value->ptr, zlrs); - } - else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { + key->zcurrent = first ? zzlFirstInLexRange(key->value->ptr,zlrs) : + zzlLastInLexRange(key->value->ptr,zlrs); + } else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { zset *zs = key->value->ptr; zskiplist *zsl = zs->zsl; - key->zcurrent = first ? zslFirstInLexRange(zsl, zlrs) : - zslLastInLexRange(zsl, zlrs); - } - else { + key->zcurrent = first ? zslFirstInLexRange(zsl,zlrs) : + zslLastInLexRange(zsl,zlrs); + } else { serverPanic("Unsupported zset encoding"); } if (key->zcurrent == NULL) key->zer = 1; @@ -1977,13 +1966,13 @@ int zsetInitLexRange(RedisModuleKey *key, RedisModuleString *min, RedisModuleStr * The function does not take ownership of the objects, so they can be released * ASAP after the iterator is setup. */ int RM_ZsetFirstInLexRange(RedisModuleKey *key, RedisModuleString *min, RedisModuleString *max) { - return zsetInitLexRange(key, min, max, 1); + return zsetInitLexRange(key,min,max,1); } /* Exactly like RedisModule_ZsetFirstInLexRange() but the last element of * the range is selected for the start of the iteration instead. */ int RM_ZsetLastInLexRange(RedisModuleKey *key, RedisModuleString *min, RedisModuleString *max) { - return zsetInitLexRange(key, min, max, 0); + return zsetInitLexRange(key,min,max,0); } /* Return the current sorted set element of an active sorted set iterator @@ -1998,20 +1987,18 @@ RedisModuleString *RM_ZsetRangeCurrentElement(RedisModuleKey *key, double *score eptr = key->zcurrent; sds ele = ziplistGetObject(eptr); if (score) { - sptr = ziplistNext(key->value->ptr, eptr); + sptr = ziplistNext(key->value->ptr,eptr); *score = zzlGetScore(sptr); } - str = createObject(OBJ_STRING, ele); - } - else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { + str = createObject(OBJ_STRING,ele); + } else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { zskiplistNode *ln = key->zcurrent; if (score) *score = ln->score; - str = createStringObject(ln->ele, sdslen(ln->ele)); - } - else { + str = createStringObject(ln->ele,sdslen(ln->ele)); + } else { serverPanic("Unsupported zset encoding"); } - autoMemoryAdd(key->ctx, REDISMODULE_AM_STRING, str); + autoMemoryAdd(key->ctx,REDISMODULE_AM_STRING,str); return str; } @@ -2025,28 +2012,26 @@ int RM_ZsetRangeNext(RedisModuleKey *key) { unsigned char *zl = key->value->ptr; unsigned char *eptr = key->zcurrent; unsigned char *next; - next = ziplistNext(zl, eptr); /* Skip element. */ - if (next) next = ziplistNext(zl, next); /* Skip score. */ + next = ziplistNext(zl,eptr); /* Skip element. */ + if (next) next = ziplistNext(zl,next); /* Skip score. */ if (next == NULL) { key->zer = 1; return 0; - } - else { + } else { /* Are we still within the range? */ if (key->ztype == REDISMODULE_ZSET_RANGE_SCORE) { /* Fetch the next element score for the * range check. */ unsigned char *saved_next = next; - next = ziplistNext(zl, next); /* Skip next element. */ + next = ziplistNext(zl,next); /* Skip next element. */ double score = zzlGetScore(next); /* Obtain the next score. */ - if (!zslValueLteMax(score, &key->zrs)) { + if (!zslValueLteMax(score,&key->zrs)) { key->zer = 1; return 0; } next = saved_next; - } - else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { - if (!zzlLexValueLteMax(next, &key->zlrs)) { + } else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { + if (!zzlLexValueLteMax(next,&key->zlrs)) { key->zer = 1; return 0; } @@ -2054,23 +2039,20 @@ int RM_ZsetRangeNext(RedisModuleKey *key) { key->zcurrent = next; return 1; } - } - else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { + } else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { zskiplistNode *ln = key->zcurrent, *next = ln->level[0].forward; if (next == NULL) { key->zer = 1; return 0; - } - else { + } else { /* Are we still within the range? */ if (key->ztype == REDISMODULE_ZSET_RANGE_SCORE && - !zslValueLteMax(next->score, &key->zrs)) + !zslValueLteMax(next->score,&key->zrs)) { key->zer = 1; return 0; - } - else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { - if (!zslLexValueLteMax(next->ele, &key->zlrs)) { + } else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { + if (!zslLexValueLteMax(next->ele,&key->zlrs)) { key->zer = 1; return 0; } @@ -2078,8 +2060,7 @@ int RM_ZsetRangeNext(RedisModuleKey *key) { key->zcurrent = next; return 1; } - } - else { + } else { serverPanic("Unsupported zset encoding"); } } @@ -2094,28 +2075,26 @@ int RM_ZsetRangePrev(RedisModuleKey *key) { unsigned char *zl = key->value->ptr; unsigned char *eptr = key->zcurrent; unsigned char *prev; - prev = ziplistPrev(zl, eptr); /* Go back to previous score. */ - if (prev) prev = ziplistPrev(zl, prev); /* Back to previous ele. */ + prev = ziplistPrev(zl,eptr); /* Go back to previous score. */ + if (prev) prev = ziplistPrev(zl,prev); /* Back to previous ele. */ if (prev == NULL) { key->zer = 1; return 0; - } - else { + } else { /* Are we still within the range? */ if (key->ztype == REDISMODULE_ZSET_RANGE_SCORE) { /* Fetch the previous element score for the * range check. */ unsigned char *saved_prev = prev; - prev = ziplistNext(zl, prev); /* Skip element to get the score.*/ + prev = ziplistNext(zl,prev); /* Skip element to get the score.*/ double score = zzlGetScore(prev); /* Obtain the prev score. */ - if (!zslValueGteMin(score, &key->zrs)) { + if (!zslValueGteMin(score,&key->zrs)) { key->zer = 1; return 0; } prev = saved_prev; - } - else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { - if (!zzlLexValueGteMin(prev, &key->zlrs)) { + } else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { + if (!zzlLexValueGteMin(prev,&key->zlrs)) { key->zer = 1; return 0; } @@ -2123,23 +2102,20 @@ int RM_ZsetRangePrev(RedisModuleKey *key) { key->zcurrent = prev; return 1; } - } - else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { + } else if (key->value->encoding == OBJ_ENCODING_SKIPLIST) { zskiplistNode *ln = key->zcurrent, *prev = ln->backward; if (prev == NULL) { key->zer = 1; return 0; - } - else { + } else { /* Are we still within the range? */ if (key->ztype == REDISMODULE_ZSET_RANGE_SCORE && - !zslValueGteMin(prev->score, &key->zrs)) + !zslValueGteMin(prev->score,&key->zrs)) { key->zer = 1; return 0; - } - else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { - if (!zslLexValueGteMin(prev->ele, &key->zlrs)) { + } else if (key->ztype == REDISMODULE_ZSET_RANGE_LEX) { + if (!zslLexValueGteMin(prev->ele,&key->zlrs)) { key->zer = 1; return 0; } @@ -2147,8 +2123,7 @@ int RM_ZsetRangePrev(RedisModuleKey *key) { key->zcurrent = prev; return 1; } - } - else { + } else { serverPanic("Unsupported zset encoding"); } } @@ -2157,80 +2132,79 @@ int RM_ZsetRangePrev(RedisModuleKey *key) { * Key API for Hash type * -------------------------------------------------------------------------- */ - /* Set the field of the specified hash field to the specified value. - * If the key is an empty key open for writing, it is created with an empty - * hash value, in order to set the specified field. - * - * The function is variadic and the user must specify pairs of field - * names and values, both as RedisModuleString pointers (unless the - * CFIELD option is set, see later). - * - * Example to set the hash argv[1] to the value argv[2]: - * - * RedisModule_HashSet(key,REDISMODULE_HASH_NONE,argv[1],argv[2],NULL); - * - * The function can also be used in order to delete fields (if they exist) - * by setting them to the specified value of REDISMODULE_HASH_DELETE: - * - * RedisModule_HashSet(key,REDISMODULE_HASH_NONE,argv[1], - * REDISMODULE_HASH_DELETE,NULL); - * - * The behavior of the command changes with the specified flags, that can be - * set to REDISMODULE_HASH_NONE if no special behavior is needed. - * - * REDISMODULE_HASH_NX: The operation is performed only if the field was not - * already existing in the hash. - * REDISMODULE_HASH_XX: The operation is performed only if the field was - * already existing, so that a new value could be - * associated to an existing filed, but no new fields - * are created. - * REDISMODULE_HASH_CFIELDS: The field names passed are null terminated C - * strings instead of RedisModuleString objects. - * - * Unless NX is specified, the command overwrites the old field value with - * the new one. - * - * When using REDISMODULE_HASH_CFIELDS, field names are reported using - * normal C strings, so for example to delete the field "foo" the following - * code can be used: - * - * RedisModule_HashSet(key,REDISMODULE_HASH_CFIELDS,"foo", - * REDISMODULE_HASH_DELETE,NULL); - * - * Return value: - * - * The number of fields updated (that may be less than the number of fields - * specified because of the XX or NX options). - * - * In the following case the return value is always zero: - * - * * The key was not open for writing. - * * The key was associated with a non Hash value. - */ +/* Set the field of the specified hash field to the specified value. + * If the key is an empty key open for writing, it is created with an empty + * hash value, in order to set the specified field. + * + * The function is variadic and the user must specify pairs of field + * names and values, both as RedisModuleString pointers (unless the + * CFIELD option is set, see later). + * + * Example to set the hash argv[1] to the value argv[2]: + * + * RedisModule_HashSet(key,REDISMODULE_HASH_NONE,argv[1],argv[2],NULL); + * + * The function can also be used in order to delete fields (if they exist) + * by setting them to the specified value of REDISMODULE_HASH_DELETE: + * + * RedisModule_HashSet(key,REDISMODULE_HASH_NONE,argv[1], + * REDISMODULE_HASH_DELETE,NULL); + * + * The behavior of the command changes with the specified flags, that can be + * set to REDISMODULE_HASH_NONE if no special behavior is needed. + * + * REDISMODULE_HASH_NX: The operation is performed only if the field was not + * already existing in the hash. + * REDISMODULE_HASH_XX: The operation is performed only if the field was + * already existing, so that a new value could be + * associated to an existing filed, but no new fields + * are created. + * REDISMODULE_HASH_CFIELDS: The field names passed are null terminated C + * strings instead of RedisModuleString objects. + * + * Unless NX is specified, the command overwrites the old field value with + * the new one. + * + * When using REDISMODULE_HASH_CFIELDS, field names are reported using + * normal C strings, so for example to delete the field "foo" the following + * code can be used: + * + * RedisModule_HashSet(key,REDISMODULE_HASH_CFIELDS,"foo", + * REDISMODULE_HASH_DELETE,NULL); + * + * Return value: + * + * The number of fields updated (that may be less than the number of fields + * specified because of the XX or NX options). + * + * In the following case the return value is always zero: + * + * * The key was not open for writing. + * * The key was associated with a non Hash value. + */ int RM_HashSet(RedisModuleKey *key, int flags, ...) { va_list ap; if (!(key->mode & REDISMODULE_WRITE)) return 0; if (key->value && key->value->type != OBJ_HASH) return 0; - if (key->value == NULL) moduleCreateEmptyKey(key, REDISMODULE_KEYTYPE_HASH); + if (key->value == NULL) moduleCreateEmptyKey(key,REDISMODULE_KEYTYPE_HASH); int updated = 0; va_start(ap, flags); - while (1) { + while(1) { RedisModuleString *field, *value; /* Get the field and value objects. */ if (flags & REDISMODULE_HASH_CFIELDS) { - char *cfield = va_arg(ap, char*); + char *cfield = va_arg(ap,char*); if (cfield == NULL) break; - field = createRawStringObject(cfield, strlen(cfield)); - } - else { - field = va_arg(ap, RedisModuleString*); + field = createRawStringObject(cfield,strlen(cfield)); + } else { + field = va_arg(ap,RedisModuleString*); if (field == NULL) break; } - value = va_arg(ap, RedisModuleString*); + value = va_arg(ap,RedisModuleString*); /* Handle XX and NX */ - if (flags & (REDISMODULE_HASH_XX | REDISMODULE_HASH_NX)) { + if (flags & (REDISMODULE_HASH_XX|REDISMODULE_HASH_NX)) { int exists = hashTypeExists(key->value, field->ptr); if (((flags & REDISMODULE_HASH_XX) && !exists) || ((flags & REDISMODULE_HASH_NX) && exists)) @@ -2258,8 +2232,8 @@ int RM_HashSet(RedisModuleKey *key, int flags, ...) { /* If CFIELDS is active, SDS string ownership is now of hashTypeSet(), * however we still have to release the 'field' object shell. */ if (flags & REDISMODULE_HASH_CFIELDS) { - field->ptr = NULL; /* Prevent the SDS string from being freed. */ - decrRefCount(field); + field->ptr = NULL; /* Prevent the SDS string from being freed. */ + decrRefCount(field); } } va_end(ap); @@ -2313,41 +2287,38 @@ int RM_HashGet(RedisModuleKey *key, int flags, ...) { if (key->value && key->value->type != OBJ_HASH) return REDISMODULE_ERR; va_start(ap, flags); - while (1) { + while(1) { RedisModuleString *field, **valueptr; int *existsptr; /* Get the field object and the value pointer to pointer. */ if (flags & REDISMODULE_HASH_CFIELDS) { - char *cfield = va_arg(ap, char*); + char *cfield = va_arg(ap,char*); if (cfield == NULL) break; - field = createRawStringObject(cfield, strlen(cfield)); - } - else { - field = va_arg(ap, RedisModuleString*); + field = createRawStringObject(cfield,strlen(cfield)); + } else { + field = va_arg(ap,RedisModuleString*); if (field == NULL) break; } /* Query the hash for existence or value object. */ if (flags & REDISMODULE_HASH_EXISTS) { - existsptr = va_arg(ap, int*); + existsptr = va_arg(ap,int*); if (key->value) - *existsptr = hashTypeExists(key->value, field->ptr); + *existsptr = hashTypeExists(key->value,field->ptr); else *existsptr = 0; - } - else { - valueptr = va_arg(ap, RedisModuleString**); + } else { + valueptr = va_arg(ap,RedisModuleString**); if (key->value) { - *valueptr = hashTypeGetValueObject(key->value, field->ptr); + *valueptr = hashTypeGetValueObject(key->value,field->ptr); if (*valueptr) { robj *decoded = getDecodedObject(*valueptr); decrRefCount(*valueptr); *valueptr = decoded; } if (*valueptr) - autoMemoryAdd(key->ctx, REDISMODULE_AM_STRING, *valueptr); - } - else { + autoMemoryAdd(key->ctx,REDISMODULE_AM_STRING,*valueptr); + } else { *valueptr = NULL; } } @@ -2363,17 +2334,17 @@ int RM_HashGet(RedisModuleKey *key, int flags, ...) { * Redis <-> Modules generic Call() API * -------------------------------------------------------------------------- */ - /* Create a new RedisModuleCallReply object. The processing of the reply - * is lazy, the object is just populated with the raw protocol and later - * is processed as needed. Initially we just make sure to set the right - * reply type, which is extremely cheap to do. */ +/* Create a new RedisModuleCallReply object. The processing of the reply + * is lazy, the object is just populated with the raw protocol and later + * is processed as needed. Initially we just make sure to set the right + * reply type, which is extremely cheap to do. */ RedisModuleCallReply *moduleCreateCallReplyFromProto(RedisModuleCtx *ctx, sds proto) { RedisModuleCallReply *reply = zmalloc(sizeof(*reply)); reply->ctx = ctx; reply->proto = proto; reply->protolen = sdslen(proto); reply->flags = REDISMODULE_REPLYFLAG_TOPARSE; /* Lazy parsing. */ - switch (proto[0]) { + switch(proto[0]) { case '$': case '+': reply->type = REDISMODULE_REPLY_STRING; break; case '-': reply->type = REDISMODULE_REPLY_ERROR; break; @@ -2398,7 +2369,7 @@ void moduleParseCallReply(RedisModuleCallReply *reply) { if (!(reply->flags & REDISMODULE_REPLYFLAG_TOPARSE)) return; reply->flags &= ~REDISMODULE_REPLYFLAG_TOPARSE; - switch (reply->proto[0]) { + switch(reply->proto[0]) { case ':': moduleParseCallReply_Int(reply); break; case '$': moduleParseCallReply_BulkString(reply); break; case '-': /* handled by next item. */ @@ -2409,52 +2380,51 @@ void moduleParseCallReply(RedisModuleCallReply *reply) { void moduleParseCallReply_Int(RedisModuleCallReply *reply) { char *proto = reply->proto; - char *p = strchr(proto + 1, '\r'); + char *p = strchr(proto+1,'\r'); - string2ll(proto + 1, p - proto - 1, &reply->val.ll); - reply->protolen = p - proto + 2; + string2ll(proto+1,p-proto-1,&reply->val.ll); + reply->protolen = p-proto+2; reply->type = REDISMODULE_REPLY_INTEGER; } void moduleParseCallReply_BulkString(RedisModuleCallReply *reply) { char *proto = reply->proto; - char *p = strchr(proto + 1, '\r'); + char *p = strchr(proto+1,'\r'); PORT_LONGLONG bulklen; - string2ll(proto + 1, p - proto - 1, &bulklen); + string2ll(proto+1,p-proto-1,&bulklen); if (bulklen == -1) { - reply->protolen = p - proto + 2; + reply->protolen = p-proto+2; reply->type = REDISMODULE_REPLY_NULL; - } - else { - reply->val.str = p + 2; + } else { + reply->val.str = p+2; reply->len = bulklen; - reply->protolen = p - proto + 2 + bulklen + 2; + reply->protolen = p-proto+2+bulklen+2; reply->type = REDISMODULE_REPLY_STRING; } } void moduleParseCallReply_SimpleString(RedisModuleCallReply *reply) { char *proto = reply->proto; - char *p = strchr(proto + 1, '\r'); + char *p = strchr(proto+1,'\r'); - reply->val.str = proto + 1; - reply->len = p - proto - 1; - reply->protolen = p - proto + 2; + reply->val.str = proto+1; + reply->len = p-proto-1; + reply->protolen = p-proto+2; reply->type = proto[0] == '+' ? REDISMODULE_REPLY_STRING : - REDISMODULE_REPLY_ERROR; + REDISMODULE_REPLY_ERROR; } void moduleParseCallReply_Array(RedisModuleCallReply *reply) { char *proto = reply->proto; - char *p = strchr(proto + 1, '\r'); + char *p = strchr(proto+1,'\r'); PORT_LONGLONG arraylen, j; - string2ll(proto + 1, p - proto - 1, &arraylen); + string2ll(proto+1,p-proto-1,&arraylen); p += 2; if (arraylen == -1) { - reply->protolen = p - proto; + reply->protolen = p-proto; reply->type = REDISMODULE_REPLY_NULL; return; } @@ -2462,21 +2432,21 @@ void moduleParseCallReply_Array(RedisModuleCallReply *reply) { reply->val.array = zmalloc(sizeof(RedisModuleCallReply)*arraylen); reply->len = arraylen; for (j = 0; j < arraylen; j++) { - RedisModuleCallReply *ele = reply->val.array + j; + RedisModuleCallReply *ele = reply->val.array+j; ele->flags = REDISMODULE_REPLYFLAG_NESTED | - REDISMODULE_REPLYFLAG_TOPARSE; + REDISMODULE_REPLYFLAG_TOPARSE; ele->proto = p; ele->ctx = reply->ctx; moduleParseCallReply(ele); p += ele->protolen; } - reply->protolen = p - proto; + reply->protolen = p-proto; reply->type = REDISMODULE_REPLY_ARRAY; } /* Free a Call reply and all the nested replies it contains if it's an * array. */ -void RM_FreeCallReply_Rec(RedisModuleCallReply *reply, int freenested) { +void RM_FreeCallReply_Rec(RedisModuleCallReply *reply, int freenested){ /* Don't free nested replies by default: the user must always free the * toplevel reply. However be gentle and don't crash if the module * misuses the API. */ @@ -2486,7 +2456,7 @@ void RM_FreeCallReply_Rec(RedisModuleCallReply *reply, int freenested) { if (reply->type == REDISMODULE_REPLY_ARRAY) { size_t j; for (j = 0; j < reply->len; j++) - RM_FreeCallReply_Rec(reply->val.array + j, 1); + RM_FreeCallReply_Rec(reply->val.array+j,1); zfree(reply->val.array); } } @@ -2505,9 +2475,10 @@ void RM_FreeCallReply_Rec(RedisModuleCallReply *reply, int freenested) { * to have the first level function to return on nested replies, but only * if called by the module API. */ void RM_FreeCallReply(RedisModuleCallReply *reply) { + RedisModuleCtx *ctx = reply->ctx; - RM_FreeCallReply_Rec(reply, 0); - autoMemoryFreed(ctx, REDISMODULE_AM_REPLY, reply); + RM_FreeCallReply_Rec(reply,0); + autoMemoryFreed(ctx,REDISMODULE_AM_REPLY,reply); } /* Return the reply type. */ @@ -2519,7 +2490,7 @@ int RM_CallReplyType(RedisModuleCallReply *reply) { /* Return the reply type length, where applicable. */ size_t RM_CallReplyLength(RedisModuleCallReply *reply) { moduleParseCallReply(reply); - switch (reply->type) { + switch(reply->type) { case REDISMODULE_REPLY_STRING: case REDISMODULE_REPLY_ERROR: case REDISMODULE_REPLY_ARRAY: @@ -2535,7 +2506,7 @@ RedisModuleCallReply *RM_CallReplyArrayElement(RedisModuleCallReply *reply, size moduleParseCallReply(reply); if (reply->type != REDISMODULE_REPLY_ARRAY) return NULL; if (idx >= reply->len) return NULL; - return reply->val.array + idx; + return reply->val.array+idx; } /* Return the PORT_LONGLONG of an integer reply. */ @@ -2558,15 +2529,15 @@ const char *RM_CallReplyStringPtr(RedisModuleCallReply *reply, size_t *len) { * integer. Otherwise (wrong reply type) return NULL. */ RedisModuleString *RM_CreateStringFromCallReply(RedisModuleCallReply *reply) { moduleParseCallReply(reply); - switch (reply->type) { + switch(reply->type) { case REDISMODULE_REPLY_STRING: case REDISMODULE_REPLY_ERROR: - return RM_CreateString(reply->ctx, reply->val.str, reply->len); + return RM_CreateString(reply->ctx,reply->val.str,reply->len); case REDISMODULE_REPLY_INTEGER: { char buf[64]; - int len = ll2string(buf, sizeof(buf), reply->val.ll); - return RM_CreateString(reply->ctx, buf, len); - } + int len = ll2string(buf,sizeof(buf),reply->val.ll); + return RM_CreateString(reply->ctx,buf,len); + } default: return NULL; } } @@ -2591,55 +2562,49 @@ robj **moduleCreateArgvFromUserFormat(const char *cmdname, const char *fmt, int /* As a first guess to avoid useless reallocations, size argv to * hold one argument for each char specifier in 'fmt'. */ - argv_size = strlen(fmt) + 1; /* +1 because of the command name. */ - argv = zrealloc(argv, sizeof(robj*)*argv_size); + argv_size = strlen(fmt)+1; /* +1 because of the command name. */ + argv = zrealloc(argv,sizeof(robj*)*argv_size); /* Build the arguments vector based on the format specifier. */ - argv[0] = createStringObject(cmdname, strlen(cmdname)); + argv[0] = createStringObject(cmdname,strlen(cmdname)); argc++; /* Create the client and dispatch the command. */ const char *p = fmt; - while (*p) { + while(*p) { if (*p == 'c') { - char *cstr = va_arg(ap, char*); - argv[argc++] = createStringObject(cstr, strlen(cstr)); - } - else if (*p == 's') { - robj *obj = va_arg(ap, void*); + char *cstr = va_arg(ap,char*); + argv[argc++] = createStringObject(cstr,strlen(cstr)); + } else if (*p == 's') { + robj *obj = va_arg(ap,void*); argv[argc++] = obj; incrRefCount(obj); - } - else if (*p == 'b') { - char *buf = va_arg(ap, char*); - size_t len = va_arg(ap, size_t); - argv[argc++] = createStringObject(buf, len); - } - else if (*p == 'l') { + } else if (*p == 'b') { + char *buf = va_arg(ap,char*); + size_t len = va_arg(ap,size_t); + argv[argc++] = createStringObject(buf,len); + } else if (*p == 'l') { PORT_LONG ll = va_arg(ap, PORT_LONGLONG); - argv[argc++] = createObject(OBJ_STRING, sdsfromlonglong(ll)); - } - else if (*p == 'v') { - /* A vector of strings */ - robj **v = va_arg(ap, void*); - size_t vlen = va_arg(ap, size_t); + argv[argc++] = createObject(OBJ_STRING,sdsfromlonglong(ll)); + } else if (*p == 'v') { + /* A vector of strings */ + robj **v = va_arg(ap, void*); + size_t vlen = va_arg(ap, size_t); - /* We need to grow argv to hold the vector's elements. - * We resize by vector_len-1 elements, because we held - * one element in argv for the vector already */ - argv_size += vlen - 1; - argv = zrealloc(argv, sizeof(robj*)*argv_size); + /* We need to grow argv to hold the vector's elements. + * We resize by vector_len-1 elements, because we held + * one element in argv for the vector already */ + argv_size += vlen-1; + argv = zrealloc(argv,sizeof(robj*)*argv_size); - size_t i = 0; - for (i = 0; i < vlen; i++) { - incrRefCount(v[i]); - argv[argc++] = v[i]; - } - } - else if (*p == '!') { + size_t i = 0; + for (i = 0; i < vlen; i++) { + incrRefCount(v[i]); + argv[argc++] = v[i]; + } + } else if (*p == '!') { if (flags) (*flags) |= REDISMODULE_ARGV_REPLICATE; - } - else { + } else { goto fmterr; } p++; @@ -2669,7 +2634,7 @@ RedisModuleCallReply *RM_Call(RedisModuleCtx *ctx, const char *cmdname, const ch RedisModuleCallReply *reply = NULL; int replicate = 0; /* Replicate this command? */ - cmd = lookupCommandByCString((char*) cmdname); + cmd = lookupCommandByCString((char*)cmdname); if (!cmd) { errno = EINVAL; return NULL; @@ -2678,7 +2643,7 @@ RedisModuleCallReply *RM_Call(RedisModuleCtx *ctx, const char *cmdname, const ch /* Create the client and dispatch the command. */ va_start(ap, fmt); c = createClient(-1); - argv = moduleCreateArgvFromUserFormat(cmdname, fmt, &argc, &flags, ap); + argv = moduleCreateArgvFromUserFormat(cmdname,fmt,&argc,&flags,ap); replicate = flags & REDISMODULE_ARGV_REPLICATE; va_end(ap); @@ -2703,10 +2668,10 @@ RedisModuleCallReply *RM_Call(RedisModuleCtx *ctx, const char *cmdname, const ch * received from our master. */ if (server.cluster_enabled && !(ctx->client->flags & CLIENT_MASTER)) { /* Duplicate relevant flags in the module client. */ - c->flags &= ~(CLIENT_READONLY | CLIENT_ASKING); - c->flags |= ctx->client->flags & (CLIENT_READONLY | CLIENT_ASKING); - if (getNodeByQuery(c, c->cmd, c->argv, c->argc, NULL, NULL) != - server.cluster->myself) + c->flags &= ~(CLIENT_READONLY|CLIENT_ASKING); + c->flags |= ctx->client->flags & (CLIENT_READONLY|CLIENT_ASKING); + if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) != + server.cluster->myself) { errno = EPERM; goto cleanup; @@ -2724,21 +2689,21 @@ RedisModuleCallReply *RM_Call(RedisModuleCtx *ctx, const char *cmdname, const ch call_flags |= CMD_CALL_PROPAGATE_AOF; call_flags |= CMD_CALL_PROPAGATE_REPL; } - call(c, call_flags); + call(c,call_flags); /* Convert the result of the Redis command into a suitable Lua type. * The first thing we need is to create a single string from the client * output buffers. */ - sds proto = sdsnewlen(c->buf, c->bufpos); + sds proto = sdsnewlen(c->buf,c->bufpos); c->bufpos = 0; - while (listLength(c->reply)) { + while(listLength(c->reply)) { sds o = listNodeValue(listFirst(c->reply)); - proto = sdscatsds(proto, o); - listDelNode(c->reply, listFirst(c->reply)); + proto = sdscatsds(proto,o); + listDelNode(c->reply,listFirst(c->reply)); } - reply = moduleCreateCallReplyFromProto(ctx, proto); - autoMemoryAdd(ctx, REDISMODULE_AM_REPLY, reply); + reply = moduleCreateCallReplyFromProto(ctx,proto); + autoMemoryAdd(ctx,REDISMODULE_AM_REPLY,reply); cleanup: freeClient(c); @@ -2762,33 +2727,33 @@ const char *RM_CallReplyProto(RedisModuleCallReply *reply, size_t *len) { * AOF rewrite, and so forth). In this section we define this API. * -------------------------------------------------------------------------- */ - /* Turn a 9 chars name in the specified charset and a 10 bit encver into - * a single 64 bit unsigned integer that represents this exact module name - * and version. This final number is called a "type ID" and is used when - * writing module exported values to RDB files, in order to re-associate the - * value to the right module to load them during RDB loading. - * - * If the string is not of the right length or the charset is wrong, or - * if encver is outside the unsigned 10 bit integer range, 0 is returned, - * otherwise the function returns the right type ID. - * - * The resulting 64 bit integer is composed as follows: - * - * (high order bits) 6|6|6|6|6|6|6|6|6|10 (low order bits) - * - * The first 6 bits value is the first character, name[0], while the last - * 6 bits value, immediately before the 10 bits integer, is name[8]. - * The last 10 bits are the encoding version. - * - * Note that a name and encver combo of "AAAAAAAAA" and 0, will produce - * zero as return value, that is the same we use to signal errors, thus - * this combination is invalid, and also useless since type names should - * try to be vary to avoid collisions. */ +/* Turn a 9 chars name in the specified charset and a 10 bit encver into + * a single 64 bit unsigned integer that represents this exact module name + * and version. This final number is called a "type ID" and is used when + * writing module exported values to RDB files, in order to re-associate the + * value to the right module to load them during RDB loading. + * + * If the string is not of the right length or the charset is wrong, or + * if encver is outside the unsigned 10 bit integer range, 0 is returned, + * otherwise the function returns the right type ID. + * + * The resulting 64 bit integer is composed as follows: + * + * (high order bits) 6|6|6|6|6|6|6|6|6|10 (low order bits) + * + * The first 6 bits value is the first character, name[0], while the last + * 6 bits value, immediately before the 10 bits integer, is name[8]. + * The last 10 bits are the encoding version. + * + * Note that a name and encver combo of "AAAAAAAAA" and 0, will produce + * zero as return value, that is the same we use to signal errors, thus + * this combination is invalid, and also useless since type names should + * try to be vary to avoid collisions. */ const char *ModuleTypeNameCharSet = -"ABCDEFGHIJKLMNOPQRSTUVWXYZ" -"abcdefghijklmnopqrstuvwxyz" -"0123456789-_"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789-_"; uint64_t moduleTypeEncodeId(const char *name, int encver) { /* We use 64 symbols so that we can map each character into 6 bits @@ -2799,9 +2764,9 @@ uint64_t moduleTypeEncodeId(const char *name, int encver) { uint64_t id = 0; for (int j = 0; j < 9; j++) { - char *p = strchr(cset, name[j]); + char *p = strchr(cset,name[j]); if (!p) return 0; - PORT_ULONG pos = p - cset; + PORT_ULONG pos = p-cset; id = (id << 6) | pos; } id = (id << 10) | encver; @@ -2820,10 +2785,10 @@ moduleType *moduleTypeLookupModuleByName(const char *name) { listIter li; listNode *ln; - listRewind(module->types, &li); - while ((ln = listNext(&li))) { + listRewind(module->types,&li); + while((ln = listNext(&li))) { moduleType *mt = ln->value; - if (memcmp(name, mt->name, sizeof(mt->name)) == 0) { + if (memcmp(name,mt->name,sizeof(mt->name)) == 0) { dictReleaseIterator(di); return mt; } @@ -2859,8 +2824,8 @@ moduleType *moduleTypeLookupModuleByID(uint64_t id) { listIter li; listNode *ln; - listRewind(module->types, &li); - while ((ln = listNext(&li))) { + listRewind(module->types,&li); + while((ln = listNext(&li))) { moduleType *this_mt = ln->value; /* Compare only the 54 bit module identifier and not the * encoding version. */ @@ -2888,7 +2853,7 @@ void moduleTypeNameByID(char *name, uint64_t moduleid) { const char *cset = ModuleTypeNameCharSet; name[9] = '\0'; - char *p = name + 8; + char *p = name+8; moduleid >>= 10; for (int j = 0; j < 9; j++) { *p-- = cset[moduleid & 63]; @@ -2961,11 +2926,11 @@ void moduleTypeNameByID(char *name, uint64_t moduleid) { * } */ moduleType *RM_CreateDataType(RedisModuleCtx *ctx, const char *name, int encver, void *typemethods_ptr) { - uint64_t id = moduleTypeEncodeId(name, encver); + uint64_t id = moduleTypeEncodeId(name,encver); if (id == 0) return NULL; if (moduleTypeLookupModuleByName(name) != NULL) return NULL; - PORT_LONG typemethods_version = ((PORT_LONG*) typemethods_ptr)[0]; + PORT_LONG typemethods_version = ((PORT_LONG*)typemethods_ptr)[0]; if (typemethods_version == 0) return NULL; struct typemethods { @@ -2987,8 +2952,8 @@ moduleType *RM_CreateDataType(RedisModuleCtx *ctx, const char *name, int encver, mt->mem_usage = tms->mem_usage; mt->digest = tms->digest; mt->free = tms->free; - memcpy(mt->name, name, sizeof(mt->name)); - listAddNodeTail(ctx->module->types, mt); + memcpy(mt->name,name,sizeof(mt->name)); + listAddNodeTail(ctx->module->types,mt); return mt; } @@ -2999,8 +2964,8 @@ moduleType *RM_CreateDataType(RedisModuleCtx *ctx, const char *name, int encver, int RM_ModuleTypeSetValue(RedisModuleKey *key, moduleType *mt, void *value) { if (!(key->mode & REDISMODULE_WRITE) || key->iter) return REDISMODULE_ERR; RM_DeleteKey(key); - robj *o = createModuleObject(mt, value); - setKey(key->db, key->key, o); + robj *o = createModuleObject(mt,value); + setKey(key->db,key->key,o); decrRefCount(o); key->value = o; return REDISMODULE_OK; @@ -3037,8 +3002,8 @@ void *RM_ModuleTypeGetValue(RedisModuleKey *key) { * RDB loading and saving functions * -------------------------------------------------------------------------- */ - /* Called when there is a load error in the context of a module. This cannot - * be recovered like for the built-in types. */ +/* Called when there is a load error in the context of a module. This cannot + * be recovered like for the built-in types. */ void moduleRDBLoadError(RedisModuleIO *io) { serverLog(LL_WARNING, "Error loading data from RDB (short read or EOF). " @@ -3046,7 +3011,7 @@ void moduleRDBLoadError(RedisModuleIO *io) { "after reading '%llu' bytes of a value.", io->type->module->name, io->type->name, - (PORT_ULONGLONG) io->bytes); + (PORT_ULONGLONG)io->bytes); exit(1); } @@ -3074,7 +3039,7 @@ saveerr: * new data types. */ uint64_t RM_LoadUnsigned(RedisModuleIO *io) { if (io->ver == 2) { - uint64_t opcode = rdbLoadLen(io->rio, NULL); + uint64_t opcode = rdbLoadLen(io->rio,NULL); if (opcode != RDB_MODULE_OPCODE_UINT) goto loaderr; } uint64_t value; @@ -3089,14 +3054,14 @@ loaderr: /* Like RedisModule_SaveUnsigned() but for signed 64 bit values. */ void RM_SaveSigned(RedisModuleIO *io, int64_t value) { - union { uint64_t u; int64_t i; } conv; + union {uint64_t u; int64_t i;} conv; conv.i = value; - RM_SaveUnsigned(io, conv.u); + RM_SaveUnsigned(io,conv.u); } /* Like RedisModule_LoadUnsigned() but for signed 64 bit values. */ int64_t RM_LoadSigned(RedisModuleIO *io) { - union { uint64_t u; int64_t i; } conv; + union {uint64_t u; int64_t i;} conv; conv.u = RM_LoadUnsigned(io); return conv.i; } @@ -3132,7 +3097,7 @@ void RM_SaveStringBuffer(RedisModuleIO *io, const char *str, size_t len) { if (retval == -1) goto saveerr; io->bytes += retval; /* Save value. */ - retval = rdbSaveRawString(io->rio, (unsigned char*) str, len); + retval = rdbSaveRawString(io->rio, (unsigned char*)str,len); if (retval == -1) goto saveerr; io->bytes += retval; return; @@ -3144,11 +3109,11 @@ saveerr: /* Implements RM_LoadString() and RM_LoadStringBuffer() */ void *moduleLoadString(RedisModuleIO *io, int plain, size_t *lenptr) { if (io->ver == 2) { - uint64_t opcode = rdbLoadLen(io->rio, NULL); + uint64_t opcode = rdbLoadLen(io->rio,NULL); if (opcode != RDB_MODULE_OPCODE_STRING) goto loaderr; } void *s = rdbGenericLoadStringObject(io->rio, - plain ? RDB_LOAD_PLAIN : RDB_LOAD_NONE, lenptr); + plain ? RDB_LOAD_PLAIN : RDB_LOAD_NONE, lenptr); if (s == NULL) goto loaderr; return s; @@ -3167,7 +3132,7 @@ loaderr: * If the data structure does not store strings as RedisModuleString objects, * the similar function RedisModule_LoadStringBuffer() could be used instead. */ RedisModuleString *RM_LoadString(RedisModuleIO *io) { - return moduleLoadString(io, 0, NULL); + return moduleLoadString(io,0,NULL); } /* Like RedisModule_LoadString() but returns an heap allocated string that @@ -3178,7 +3143,7 @@ RedisModuleString *RM_LoadString(RedisModuleIO *io) { * The returned string is not automatically NULL termianted, it is loaded * exactly as it was stored inisde the RDB file. */ char *RM_LoadStringBuffer(RedisModuleIO *io, size_t *lenptr) { - return moduleLoadString(io, 1, lenptr); + return moduleLoadString(io,1,lenptr); } /* In the context of the rdb_save method of a module data type, saves a double @@ -3204,7 +3169,7 @@ saveerr: * double value saved by RedisModule_SaveDouble(). */ double RM_LoadDouble(RedisModuleIO *io) { if (io->ver == 2) { - uint64_t opcode = rdbLoadLen(io->rio, NULL); + uint64_t opcode = rdbLoadLen(io->rio,NULL); if (opcode != RDB_MODULE_OPCODE_DOUBLE) goto loaderr; } double value; @@ -3240,7 +3205,7 @@ saveerr: * float value saved by RedisModule_SaveFloat(). */ float RM_LoadFloat(RedisModuleIO *io) { if (io->ver == 2) { - uint64_t opcode = rdbLoadLen(io->rio, NULL); + uint64_t opcode = rdbLoadLen(io->rio,NULL); if (opcode != RDB_MODULE_OPCODE_FLOAT) goto loaderr; } float value; @@ -3257,71 +3222,71 @@ loaderr: * Key digest API (DEBUG DIGEST interface for modules types) * -------------------------------------------------------------------------- */ - /* Add a new element to the digest. This function can be called multiple times - * one element after the other, for all the elements that constitute a given - * data structure. The function call must be followed by the call to - * `RedisModule_DigestEndSequence` eventually, when all the elements that are - * always in a given order are added. See the Redis Modules data types - * documentation for more info. However this is a quick example that uses Redis - * data types as an example. - * - * To add a sequence of unordered elements (for example in the case of a Redis - * Set), the pattern to use is: - * - * foreach element { - * AddElement(element); - * EndSequence(); - * } - * - * Because Sets are not ordered, so every element added has a position that - * does not depend from the other. However if instead our elements are - * ordered in pairs, like field-value pairs of an Hash, then one should - * use: - * - * foreach key,value { - * AddElement(key); - * AddElement(value); - * EndSquence(); - * } - * - * Because the key and value will be always in the above order, while instead - * the single key-value pairs, can appear in any position into a Redis hash. - * - * A list of ordered elements would be implemented with: - * - * foreach element { - * AddElement(element); - * } - * EndSequence(); - * - */ +/* Add a new element to the digest. This function can be called multiple times + * one element after the other, for all the elements that constitute a given + * data structure. The function call must be followed by the call to + * `RedisModule_DigestEndSequence` eventually, when all the elements that are + * always in a given order are added. See the Redis Modules data types + * documentation for more info. However this is a quick example that uses Redis + * data types as an example. + * + * To add a sequence of unordered elements (for example in the case of a Redis + * Set), the pattern to use is: + * + * foreach element { + * AddElement(element); + * EndSequence(); + * } + * + * Because Sets are not ordered, so every element added has a position that + * does not depend from the other. However if instead our elements are + * ordered in pairs, like field-value pairs of an Hash, then one should + * use: + * + * foreach key,value { + * AddElement(key); + * AddElement(value); + * EndSquence(); + * } + * + * Because the key and value will be always in the above order, while instead + * the single key-value pairs, can appear in any position into a Redis hash. + * + * A list of ordered elements would be implemented with: + * + * foreach element { + * AddElement(element); + * } + * EndSequence(); + * + */ void RM_DigestAddStringBuffer(RedisModuleDigest *md, unsigned char *ele, size_t len) { - mixDigest(md->o, ele, len); + mixDigest(md->o,ele,len); } /* Like `RedisModule_DigestAddStringBuffer()` but takes a long long as input * that gets converted into a string before adding it to the digest. */ void RM_DigestAddLongLong(RedisModuleDigest *md, PORT_LONGLONG ll) { char buf[LONG_STR_SIZE]; - size_t len = ll2string(buf, sizeof(buf), ll); - mixDigest(md->o, buf, len); + size_t len = ll2string(buf,sizeof(buf),ll); + mixDigest(md->o,buf,len); } /* See the doucmnetation for `RedisModule_DigestAddElement()`. */ void RM_DigestEndSequence(RedisModuleDigest *md) { - xorDigest(md->x, md->o, sizeof(md->o)); - memset(md->o, 0, sizeof(md->o)); + xorDigest(md->x,md->o,sizeof(md->o)); + memset(md->o,0,sizeof(md->o)); } /* -------------------------------------------------------------------------- * AOF API for modules data types * -------------------------------------------------------------------------- */ - /* Emits a command into the AOF during the AOF rewriting process. This function - * is only called in the context of the aof_rewrite method of data types exported - * by a module. The command works exactly like RedisModule_Call() in the way - * the parameters are passed, but it does not return anything as the error - * handling is performed by Redis itself. */ +/* Emits a command into the AOF during the AOF rewriting process. This function + * is only called in the context of the aof_rewrite method of data types exported + * by a module. The command works exactly like RedisModule_Call() in the way + * the parameters are passed, but it does not return anything as the error + * handling is performed by Redis itself. */ void RM_EmitAOF(RedisModuleIO *io, const char *cmdname, const char *fmt, ...) { if (io->error) return; struct redisCommand *cmd; @@ -3329,7 +3294,7 @@ void RM_EmitAOF(RedisModuleIO *io, const char *cmdname, const char *fmt, ...) { int argc = 0, flags = 0, j; va_list ap; - cmd = lookupCommandByCString((char*) cmdname); + cmd = lookupCommandByCString((char*)cmdname); if (!cmd) { serverLog(LL_WARNING, "Fatal: AOF method for module data type '%s' tried to " @@ -3342,7 +3307,7 @@ void RM_EmitAOF(RedisModuleIO *io, const char *cmdname, const char *fmt, ...) { /* Emit the arguments into the AOF in Redis protocol format. */ va_start(ap, fmt); - argv = moduleCreateArgvFromUserFormat(cmdname, fmt, &argc, &flags, ap); + argv = moduleCreateArgvFromUserFormat(cmdname,fmt,&argc,&flags,ap); va_end(ap); if (argv == NULL) { serverLog(LL_WARNING, @@ -3355,12 +3320,12 @@ void RM_EmitAOF(RedisModuleIO *io, const char *cmdname, const char *fmt, ...) { } /* Bulk count. */ - if (!io->error && rioWriteBulkCount(io->rio, '*', argc) == 0) + if (!io->error && rioWriteBulkCount(io->rio,'*',argc) == 0) io->error = 1; /* Arguments. */ for (j = 0; j < argc; j++) { - if (!io->error && rioWriteBulkObject(io->rio, argv[j]) == 0) + if (!io->error && rioWriteBulkObject(io->rio,argv[j]) == 0) io->error = 1; decrRefCount(argv[j]); } @@ -3386,26 +3351,26 @@ RedisModuleCtx *RM_GetContextFromIO(RedisModuleIO *io) { * Logging * -------------------------------------------------------------------------- */ - /* This is the low level function implementing both: - * - * RM_Log() - * RM_LogIOError() - * - */ +/* This is the low level function implementing both: + * + * RM_Log() + * RM_LogIOError() + * + */ void RM_LogRaw(RedisModule *module, const char *levelstr, const char *fmt, va_list ap) { char msg[LOG_MAX_LEN]; size_t name_len; int level; - if (!strcasecmp(levelstr, "debug")) level = LL_DEBUG; - else if (!strcasecmp(levelstr, "verbose")) level = LL_VERBOSE; - else if (!strcasecmp(levelstr, "notice")) level = LL_NOTICE; - else if (!strcasecmp(levelstr, "warning")) level = LL_WARNING; + if (!strcasecmp(levelstr,"debug")) level = LL_DEBUG; + else if (!strcasecmp(levelstr,"verbose")) level = LL_VERBOSE; + else if (!strcasecmp(levelstr,"notice")) level = LL_NOTICE; + else if (!strcasecmp(levelstr,"warning")) level = LL_WARNING; else level = LL_VERBOSE; /* Default. */ - name_len = snprintf(msg, sizeof(msg), "<%s> ", module->name); + name_len = snprintf(msg, sizeof(msg),"<%s> ", module->name); vsnprintf(msg + name_len, sizeof(msg) - name_len, fmt, ap); - serverLogRaw(level, msg); + serverLogRaw(level,msg); } /* Produces a log message to the standard Redis log, the format accepts @@ -3427,7 +3392,7 @@ void RM_Log(RedisModuleCtx *ctx, const char *levelstr, const char *fmt, ...) { va_list ap; va_start(ap, fmt); - RM_LogRaw(ctx->module, levelstr, fmt, ap); + RM_LogRaw(ctx->module,levelstr,fmt,ap); va_end(ap); } @@ -3439,7 +3404,7 @@ void RM_Log(RedisModuleCtx *ctx, const char *levelstr, const char *fmt, ...) { void RM_LogIOError(RedisModuleIO *io, const char *levelstr, const char *fmt, ...) { va_list ap; va_start(ap, fmt); - RM_LogRaw(io->type->module, levelstr, fmt, ap); + RM_LogRaw(io->type->module,levelstr,fmt,ap); va_end(ap); } @@ -3447,10 +3412,10 @@ void RM_LogIOError(RedisModuleIO *io, const char *levelstr, const char *fmt, ... * Blocking clients from modules * -------------------------------------------------------------------------- */ - /* Readable handler for the awake pipe. We do nothing here, the awake bytes - * will be actually read in a more appropriate place in the - * moduleHandleBlockedClients() function that is where clients are actually - * served. */ +/* Readable handler for the awake pipe. We do nothing here, the awake bytes + * will be actually read in a more appropriate place in the + * moduleHandleBlockedClients() function that is where clients are actually + * served. */ void moduleBlockedClientPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(fd); @@ -3496,7 +3461,7 @@ void unblockClientFromModule(client *c) { * free_privdata: called in order to free the privata data that is passed * by RedisModule_UnblockClient() call. */ -RedisModuleBlockedClient *RM_BlockClient(RedisModuleCtx *ctx, RedisModuleCmdFunc reply_callback, RedisModuleCmdFunc timeout_callback, void(*free_privdata)(void*), PORT_LONGLONG timeout_ms) { +RedisModuleBlockedClient *RM_BlockClient(RedisModuleCtx *ctx, RedisModuleCmdFunc reply_callback, RedisModuleCmdFunc timeout_callback, void (*free_privdata)(void*), PORT_LONGLONG timeout_ms) { client *c = ctx->client; int islua = c->flags & CLIENT_LUA; int ismulti = c->flags & CLIENT_MULTI; @@ -3517,7 +3482,7 @@ RedisModuleBlockedClient *RM_BlockClient(RedisModuleCtx *ctx, RedisModuleCmdFunc bc->reply_client = createClient(-1); bc->reply_client->flags |= CLIENT_MODULE; bc->dbid = c->db->id; - c->bpop.timeout = timeout_ms ? (mstime() + timeout_ms) : 0; + c->bpop.timeout = timeout_ms ? (mstime()+timeout_ms) : 0; if (islua || ismulti) { c->bpop.module_blocked_handle = NULL; @@ -3544,8 +3509,8 @@ RedisModuleBlockedClient *RM_BlockClient(RedisModuleCtx *ctx, RedisModuleCmdFunc int RM_UnblockClient(RedisModuleBlockedClient *bc, void *privdata) { pthread_mutex_lock(&moduleUnblockedClientsMutex); bc->privdata = privdata; - listAddNodeTail(moduleUnblockedClients, bc); - if (write(server.module_blocked_pipe[1], "A", 1) != 1) { + listAddNodeTail(moduleUnblockedClients,bc); + if (write(server.module_blocked_pipe[1],"A",1) != 1) { /* Ignore the error, this is best-effort. */ } pthread_mutex_unlock(&moduleUnblockedClientsMutex); @@ -3556,7 +3521,7 @@ int RM_UnblockClient(RedisModuleBlockedClient *bc, void *privdata) { * without firing the reply callback. */ int RM_AbortBlock(RedisModuleBlockedClient *bc) { bc->reply_callback = NULL; - return RM_UnblockClient(bc, NULL); + return RM_UnblockClient(bc,NULL); } /* This function will check the moduleUnblockedClients queue in order to @@ -3575,26 +3540,26 @@ void moduleHandleBlockedClients(void) { /* Here we unblock all the pending clients blocked in modules operations * so we can read every pending "awake byte" in the pipe. */ char buf[1]; - while (read(server.module_blocked_pipe[0], buf, 1) == 1); + while (read(server.module_blocked_pipe[0],buf,1) == 1); while (listLength(moduleUnblockedClients)) { ln = listFirst(moduleUnblockedClients); bc = ln->value; client *c = bc->client; - listDelNode(moduleUnblockedClients, ln); + listDelNode(moduleUnblockedClients,ln); pthread_mutex_unlock(&moduleUnblockedClientsMutex); /* Release the lock during the loop, as long as we don't * touch the shared list. */ - /* Call the reply callback if the client is valid and we have - * any callback. */ + /* Call the reply callback if the client is valid and we have + * any callback. */ if (c && bc->reply_callback) { RedisModuleCtx ctx = REDISMODULE_CTX_INIT; ctx.flags |= REDISMODULE_CTX_BLOCKED_REPLY; ctx.blocked_privdata = bc->privdata; ctx.module = bc->module; ctx.client = bc->client; - bc->reply_callback(&ctx, (void**) c->argv, c->argc); + bc->reply_callback(&ctx,(void**)c->argv,c->argc); moduleHandlePropagationAfterCommandCallback(&ctx); moduleFreeContext(&ctx); } @@ -3609,10 +3574,10 @@ void moduleHandleBlockedClients(void) { * free the temporary client we just used for the replies. */ if (c) { if (bc->reply_client->bufpos) - addReplyString(c, bc->reply_client->buf, - bc->reply_client->bufpos); + addReplyString(c,bc->reply_client->buf, + bc->reply_client->bufpos); if (listLength(bc->reply_client->reply)) - listJoin(c->reply, bc->reply_client->reply); + listJoin(c->reply,bc->reply_client->reply); c->reply_bytes += bc->reply_client->reply_bytes; } freeClient(bc->reply_client); @@ -3626,7 +3591,7 @@ void moduleHandleBlockedClients(void) { !(c->flags & CLIENT_PENDING_WRITE)) { c->flags |= CLIENT_PENDING_WRITE; - listAddNodeHead(server.clients_pending_write, c); + listAddNodeHead(server.clients_pending_write,c); } } @@ -3651,7 +3616,7 @@ void moduleBlockedClientTimedOut(client *c) { ctx.flags |= REDISMODULE_CTX_BLOCKED_TIMEOUT; ctx.module = bc->module; ctx.client = bc->client; - bc->timeout_callback(&ctx, (void**) c->argv, c->argc); + bc->timeout_callback(&ctx,(void**)c->argv,c->argc); moduleFreeContext(&ctx); } @@ -3676,29 +3641,29 @@ void *RM_GetBlockedClientPrivateData(RedisModuleCtx *ctx) { * Thread Safe Contexts * -------------------------------------------------------------------------- */ - /* Return a context which can be used inside threads to make Redis context - * calls with certain modules APIs. If 'bc' is not NULL then the module will - * be bound to a blocked client, and it will be possible to use the - * `RedisModule_Reply*` family of functions to accumulate a reply for when the - * client will be unblocked. Otherwise the thread safe context will be - * detached by a specific client. - * - * To call non-reply APIs, the thread safe context must be prepared with: - * - * RedisModule_ThreadSafeCallStart(ctx); - * ... make your call here ... - * RedisModule_ThreadSafeCallStop(ctx); - * - * This is not needed when using `RedisModule_Reply*` functions, assuming - * that a blocked client was used when the context was created, otherwise - * no RedisModule_Reply* call should be made at all. - * - * TODO: thread safe contexts do not inherit the blocked client - * selected database. */ +/* Return a context which can be used inside threads to make Redis context + * calls with certain modules APIs. If 'bc' is not NULL then the module will + * be bound to a blocked client, and it will be possible to use the + * `RedisModule_Reply*` family of functions to accumulate a reply for when the + * client will be unblocked. Otherwise the thread safe context will be + * detached by a specific client. + * + * To call non-reply APIs, the thread safe context must be prepared with: + * + * RedisModule_ThreadSafeCallStart(ctx); + * ... make your call here ... + * RedisModule_ThreadSafeCallStop(ctx); + * + * This is not needed when using `RedisModule_Reply*` functions, assuming + * that a blocked client was used when the context was created, otherwise + * no RedisModule_Reply* call should be made at all. + * + * TODO: thread safe contexts do not inherit the blocked client + * selected database. */ RedisModuleCtx *RM_GetThreadSafeContext(RedisModuleBlockedClient *bc) { RedisModuleCtx *ctx = zmalloc(sizeof(*ctx)); RedisModuleCtx empty = REDISMODULE_CTX_INIT; - memcpy(ctx, &empty, sizeof(empty)); + memcpy(ctx,&empty,sizeof(empty)); if (bc) { ctx->blocked_client = bc; ctx->module = bc->module; @@ -3709,7 +3674,7 @@ RedisModuleCtx *RM_GetThreadSafeContext(RedisModuleBlockedClient *bc) { * in order to keep things like the currently selected database and similar * things. */ ctx->client = createClient(-1); - if (bc) selectDb(ctx->client, bc->dbid); + if (bc) selectDb(ctx->client,bc->dbid); return ctx; } @@ -3859,16 +3824,16 @@ void moduleUnsubscribeNotifications(RedisModule *module) { * Modules API internals * -------------------------------------------------------------------------- */ - /* server.moduleapi dictionary type. Only uses plain C strings since - * this gets queries from modules. */ +/* server.moduleapi dictionary type. Only uses plain C strings since + * this gets queries from modules. */ uint64_t dictCStringKeyHash(const void *key) { - return dictGenHashFunction((unsigned char*) key, strlen((char*) key)); + return dictGenHashFunction((unsigned char*)key, strlen((char*)key)); } int dictCStringKeyCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); - return strcmp(key1, key2) == 0; + return strcmp(key1,key2) == 0; } dictType moduleAPIDictType = { @@ -3881,7 +3846,7 @@ dictType moduleAPIDictType = { }; int moduleRegisterApi(const char *funcname, void *funcptr) { - return dictAdd(server.moduleapi, (char*) funcname, funcptr); + return dictAdd(server.moduleapi, (char*)funcname, funcptr); } #define REGISTER_API(name) \ @@ -3892,7 +3857,6 @@ void moduleRegisterCoreAPI(void); void moduleInitModulesSystem(void) { moduleUnblockedClients = listCreate(); - server.loadmodule_queue = listCreate(); modules = dictCreate(&modulesDictType,NULL); @@ -3910,8 +3874,8 @@ void moduleInitModulesSystem(void) { } /* Make the pipe non blocking. This is just a best effort aware mechanism * and we do not want to block not in the read nor in the write half. */ - anetNonBlock(NULL, server.module_blocked_pipe[0]); - anetNonBlock(NULL, server.module_blocked_pipe[1]); + anetNonBlock(NULL,server.module_blocked_pipe[0]); + anetNonBlock(NULL,server.module_blocked_pipe[1]); /* Our thread-safe contexts GIL must start with already locked: * it is just unlocked when it's safe. */ @@ -3931,10 +3895,10 @@ void moduleLoadFromQueue(void) { listIter li; listNode *ln; - listRewind(server.loadmodule_queue, &li); - while ((ln = listNext(&li))) { + listRewind(server.loadmodule_queue,&li); + while((ln = listNext(&li))) { struct moduleLoadQueueEntry *loadmod = ln->value; - if (moduleLoad(loadmod->path, (void **) loadmod->argv, loadmod->argc) + if (moduleLoad(loadmod->path,(void **)loadmod->argv,loadmod->argc) == C_ERR) { serverLog(LL_WARNING, @@ -3976,20 +3940,20 @@ void moduleUnregisterCommands(struct RedisModule *module) { /* Load a module and initialize it. On success C_OK is returned, otherwise * C_ERR is returned. */ int moduleLoad(const char *path, void **module_argv, int module_argc) { - int(*onload)(void *, void **, int); + int (*onload)(void *, void **, int); void *handle; RedisModuleCtx ctx = REDISMODULE_CTX_INIT; - handle = dlopen(path, RTLD_NOW | RTLD_LOCAL); + handle = dlopen(path,RTLD_NOW|RTLD_LOCAL); if (handle == NULL) { serverLog(LL_WARNING, "Module %s failed to load: %s", path, dlerror()); return C_ERR; } - onload = (int(*)(void *, void **, int))(PORT_ULONG) dlsym(handle, "RedisModule_OnLoad"); + onload = (int (*)(void *, void **, int))(PORT_ULONG) dlsym(handle,"RedisModule_OnLoad"); if (onload == NULL) { serverLog(LL_WARNING, "Module %s does not export RedisModule_OnLoad() " - "symbol. Module not loaded.", path); + "symbol. Module not loaded.",path); return C_ERR; } if (onload((void*)&ctx,module_argv,module_argc) == REDISMODULE_ERR) { @@ -3999,18 +3963,19 @@ int moduleLoad(const char *path, void **module_argv, int module_argc) { } dlclose(handle); serverLog(LL_WARNING, - "Module %s initialization failed. Module not loaded", path); + "Module %s initialization failed. Module not loaded",path); return C_ERR; } /* Redis module loaded! Register it. */ - dictAdd(modules, ctx.module->name, ctx.module); + dictAdd(modules,ctx.module->name,ctx.module); ctx.module->handle = handle; - serverLog(LL_NOTICE, "Module '%s' loaded from %s", ctx.module->name, path); + serverLog(LL_NOTICE,"Module '%s' loaded from %s",ctx.module->name,path); moduleFreeContext(&ctx); return C_OK; } + /* Unload the module registered with the specified name. On success * C_OK is returned, otherwise C_ERR is returned and errno is set * to the following values depending on the type of error: @@ -4018,7 +3983,7 @@ int moduleLoad(const char *path, void **module_argv, int module_argc) { * * ENONET: No such module having the specified name. * * EBUSY: The module exports a new data type and can only be reloaded. */ int moduleUnload(sds name) { - struct RedisModule *module = dictFetchValue(modules, name); + struct RedisModule *module = dictFetchValue(modules,name); if (module == NULL) { errno = ENOENT; @@ -4032,7 +3997,7 @@ int moduleUnload(sds name) { moduleUnregisterCommands(module); - /* Remvoe any notification subscribers this module might have */ + /* Remvoe any noification subscribers this module might have */ moduleUnsubscribeNotifications(module); /* Unregister all the hooks. TODO: Yet no hooks support here. */ @@ -4041,13 +4006,13 @@ int moduleUnload(sds name) { if (dlclose(module->handle) == -1) { char *error = dlerror(); if (error == NULL) error = "Unknown error"; - serverLog(LL_WARNING, "Error when trying to close the %s module: %s", + serverLog(LL_WARNING,"Error when trying to close the %s module: %s", module->name, error); } /* Remove from list of modules. */ - serverLog(LL_NOTICE, "Module %s unloaded", module->name); - dictDelete(modules, module->name); + serverLog(LL_NOTICE,"Module %s unloaded",module->name); + dictDelete(modules,module->name); module->name = NULL; /* The name was already freed by dictDelete(). */ moduleFreeModuleStructure(module); @@ -4060,7 +4025,7 @@ int moduleUnload(sds name) { void moduleCommand(client *c) { char *subcmd = c->argv[1]->ptr; - if (!strcasecmp(subcmd, "load") && c->argc >= 3) { + if (!strcasecmp(subcmd,"load") && c->argc >= 3) { robj **argv = NULL; int argc = 0; @@ -4069,18 +4034,17 @@ void moduleCommand(client *c) { argv = &c->argv[3]; } - if (moduleLoad(c->argv[2]->ptr, (void **) argv, argc) == C_OK) - addReply(c, shared.ok); + if (moduleLoad(c->argv[2]->ptr,(void **)argv,argc) == C_OK) + addReply(c,shared.ok); else addReplyError(c, "Error loading the extension. Please check the server logs."); - } - else if (!strcasecmp(subcmd, "unload") && c->argc == 3) { + } else if (!strcasecmp(subcmd,"unload") && c->argc == 3) { if (moduleUnload(c->argv[2]->ptr) == C_OK) - addReply(c, shared.ok); + addReply(c,shared.ok); else { char *errmsg; - switch (errno) { + switch(errno) { case ENOENT: errmsg = "no such module with that name"; break; @@ -4091,27 +4055,25 @@ void moduleCommand(client *c) { errmsg = "operation not possible."; break; } - addReplyErrorFormat(c, "Error unloading module: %s", errmsg); + addReplyErrorFormat(c,"Error unloading module: %s",errmsg); } - } - else if (!strcasecmp(subcmd, "list") && c->argc == 2) { + } else if (!strcasecmp(subcmd,"list") && c->argc == 2) { dictIterator *di = dictGetIterator(modules); dictEntry *de; - addReplyMultiBulkLen(c, dictSize(modules)); + addReplyMultiBulkLen(c,dictSize(modules)); while ((de = dictNext(di)) != NULL) { sds name = dictGetKey(de); struct RedisModule *module = dictGetVal(de); - addReplyMultiBulkLen(c, 4); - addReplyBulkCString(c, "name"); - addReplyBulkCBuffer(c, name, sdslen(name)); - addReplyBulkCString(c, "ver"); - addReplyLongLong(c, module->ver); + addReplyMultiBulkLen(c,4); + addReplyBulkCString(c,"name"); + addReplyBulkCBuffer(c,name,sdslen(name)); + addReplyBulkCString(c,"ver"); + addReplyLongLong(c,module->ver); } dictReleaseIterator(di); - } - else { - addReply(c, shared.syntaxerr); + } else { + addReply(c,shared.syntaxerr); } } @@ -4123,7 +4085,7 @@ size_t moduleCount(void) { /* Register all the APIs we export. Keep this function at the end of the * file so that's easy to seek it to add new entries. */ void moduleRegisterCoreAPI(void) { - server.moduleapi = dictCreate(&moduleAPIDictType, NULL); + server.moduleapi = dictCreate(&moduleAPIDictType,NULL); REGISTER_API(Alloc); REGISTER_API(Calloc); REGISTER_API(Realloc);