diff --git a/cmake/Modules/SourceFiles.cmake b/cmake/Modules/SourceFiles.cmake index 2845a350192..e2cd375bcc7 100644 --- a/cmake/Modules/SourceFiles.cmake +++ b/cmake/Modules/SourceFiles.cmake @@ -10,7 +10,6 @@ set(VALKEY_SERVER_SRCS ${CMAKE_SOURCE_DIR}/src/quicklist.c ${CMAKE_SOURCE_DIR}/src/ae.c ${CMAKE_SOURCE_DIR}/src/anet.c - ${CMAKE_SOURCE_DIR}/src/dict.c ${CMAKE_SOURCE_DIR}/src/hashtable.c ${CMAKE_SOURCE_DIR}/src/kvstore.c ${CMAKE_SOURCE_DIR}/src/sds.c @@ -128,7 +127,7 @@ set(VALKEY_SERVER_SRCS set(VALKEY_CLI_SRCS ${CMAKE_SOURCE_DIR}/src/anet.c ${CMAKE_SOURCE_DIR}/src/adlist.c - ${CMAKE_SOURCE_DIR}/src/dict.c + ${CMAKE_SOURCE_DIR}/src/hashtable.c ${CMAKE_SOURCE_DIR}/src/sds.c ${CMAKE_SOURCE_DIR}/src/sha256.c ${CMAKE_SOURCE_DIR}/src/util.c @@ -159,7 +158,7 @@ set(VALKEY_BENCHMARK_SRCS ${CMAKE_SOURCE_DIR}/src/valkey-benchmark.c ${CMAKE_SOURCE_DIR}/src/valkey_strtod.c ${CMAKE_SOURCE_DIR}/src/adlist.c - ${CMAKE_SOURCE_DIR}/src/dict.c + ${CMAKE_SOURCE_DIR}/src/hashtable.c ${CMAKE_SOURCE_DIR}/src/zmalloc.c ${CMAKE_SOURCE_DIR}/src/serverassert.c ${CMAKE_SOURCE_DIR}/src/release.c diff --git a/deps/CMakeLists.txt b/deps/CMakeLists.txt index 661689cc53c..b385d9df7e7 100644 --- a/deps/CMakeLists.txt +++ b/deps/CMakeLists.txt @@ -25,8 +25,7 @@ if (USE_RDMA) # Module or no module set(ENABLE_DLOPEN_RDMA ON CACHE BOOL "Build valkey_rdma with dynamic loading") endif() endif () -# Let libvalkey use sds and dict provided by valkey. -set(DICT_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/src) +# Let libvalkey use sds provided by valkey. set(SDS_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/src) add_subdirectory(libvalkey) diff --git a/deps/Makefile b/deps/Makefile index 94d938552d3..2b8af56041a 100644 --- a/deps/Makefile +++ b/deps/Makefile @@ -46,7 +46,7 @@ distclean: .PHONY: distclean -LIBVALKEY_MAKE_FLAGS = SDS_INCLUDE_DIR=../../src/ DICT_INCLUDE_DIR=../../src/ +LIBVALKEY_MAKE_FLAGS = SDS_INCLUDE_DIR=../../src/ ifneq (,$(filter $(BUILD_TLS),yes module)) LIBVALKEY_MAKE_FLAGS += USE_TLS=1 endif diff --git a/deps/libvalkey/CMakeLists.txt b/deps/libvalkey/CMakeLists.txt index c3632089ba4..08c48d63fc1 100644 --- a/deps/libvalkey/CMakeLists.txt +++ b/deps/libvalkey/CMakeLists.txt @@ -46,19 +46,16 @@ set(valkey_sources src/command.c src/conn.c src/crc16.c + src/dict.c src/net.c src/read.c src/sockcompat.c src/valkey.c src/vkutil.c) -# Allow the libvalkey provided sds and dict types to be replaced by +# Allow the libvalkey provided sds type to be replaced by # compatible implementations (like Valkey's). # A replaced type is not included in a built archive or shared library. -if(NOT DICT_INCLUDE_DIR) - set(valkey_sources ${valkey_sources} src/dict.c) - set(DICT_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) -endif() if(NOT SDS_INCLUDE_DIR) set(valkey_sources ${valkey_sources} src/sds.c) set(SDS_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) @@ -107,7 +104,6 @@ TARGET_INCLUDE_DIRECTORIES(valkey $ $ PRIVATE - $ $ ) @@ -212,7 +208,6 @@ IF(ENABLE_TLS) PRIVATE $ $ - $ $ ) @@ -289,7 +284,6 @@ if(ENABLE_RDMA) PRIVATE $ $ - $ $ ) diff --git a/deps/libvalkey/Makefile b/deps/libvalkey/Makefile index 90a70aa41d8..fbde70d02e6 100644 --- a/deps/libvalkey/Makefile +++ b/deps/libvalkey/Makefile @@ -22,13 +22,9 @@ HEADERS = $(filter-out $(INCLUDE_DIR)/tls.h $(INCLUDE_DIR)/rdma.h, $(wildcard $( # compatible implementations (like Valkey's). # A replaced type is not included in a built archive or shared library. SDS_INCLUDE_DIR ?= $(SRC_DIR) -DICT_INCLUDE_DIR ?= $(SRC_DIR) ifneq ($(SDS_INCLUDE_DIR),$(SRC_DIR)) SOURCES := $(filter-out $(SRC_DIR)/sds.c, $(SOURCES)) endif -ifneq ($(DICT_INCLUDE_DIR),$(SRC_DIR)) - SOURCES := $(filter-out $(SRC_DIR)/dict.c, $(SOURCES)) -endif OBJS = $(patsubst $(SRC_DIR)/%.c,$(OBJ_DIR)/%.o,$(SOURCES)) @@ -268,10 +264,10 @@ $(RDMA_STLIBNAME): $(RDMA_OBJS) $(STLIB_MAKE_CMD) $(RDMA_STLIBNAME) $(RDMA_OBJS) $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR) - $(CC) -std=c99 -pedantic $(REAL_CFLAGS) -I$(INCLUDE_DIR) -I$(SDS_INCLUDE_DIR) -I$(DICT_INCLUDE_DIR) -MMD -MP -c $< -o $@ + $(CC) -std=c99 -pedantic $(REAL_CFLAGS) -I$(INCLUDE_DIR) -I$(SDS_INCLUDE_DIR) -MMD -MP -c $< -o $@ $(OBJ_DIR)/%.o: $(TEST_DIR)/%.c | $(OBJ_DIR) - $(CC) -std=c99 -pedantic $(REAL_CFLAGS) -I$(INCLUDE_DIR) -I$(SDS_INCLUDE_DIR) -I$(DICT_INCLUDE_DIR) -I$(SRC_DIR) -MMD -MP -c $< -o $@ + $(CC) -std=c99 -pedantic $(REAL_CFLAGS) -I$(INCLUDE_DIR) -I$(SDS_INCLUDE_DIR) -I$(SRC_DIR) -MMD -MP -c $< -o $@ $(TEST_DIR)/%: $(OBJ_DIR)/%.o $(STLIBNAME) $(TLS_STLIB) $(CC) -o $@ $< $(RDMA_STLIB) $(STLIBNAME) $(TLS_STLIB) $(REAL_LDFLAGS) $(TEST_LDFLAGS) diff --git a/deps/libvalkey/src/async.c b/deps/libvalkey/src/async.c index c930a43e609..259dd9c53d5 100644 --- a/deps/libvalkey/src/async.c +++ b/deps/libvalkey/src/async.c @@ -47,8 +47,8 @@ #include "net.h" #include "valkey_private.h" #include "vkutil.h" +#include "dict.h" -#include #include #include diff --git a/deps/libvalkey/src/cluster.c b/deps/libvalkey/src/cluster.c index 7a20240a2ae..c775b6f0d50 100644 --- a/deps/libvalkey/src/cluster.c +++ b/deps/libvalkey/src/cluster.c @@ -39,8 +39,8 @@ #include "alloc.h" #include "command.h" #include "vkutil.h" +#include "dict.h" -#include #include #include diff --git a/src/Makefile b/src/Makefile index 73815ac2bcf..b2e14c37adb 100644 --- a/src/Makefile +++ b/src/Makefile @@ -478,7 +478,6 @@ ENGINE_SERVER_OBJ = \ db.o \ debug.o \ defrag.o \ - dict.o \ entry.o \ eval.o \ evict.o \ @@ -574,7 +573,7 @@ ENGINE_CLI_OBJ = \ crc64.o \ crccombine.o \ crcspeed.o \ - dict.o \ + hashtable.o \ monotonic.o \ mt19937-64.o \ release.o \ @@ -598,9 +597,9 @@ ENGINE_BENCHMARK_OBJ = \ crc64.o \ crccombine.o \ crcspeed.o \ - dict.o \ fuzzer_client.o \ fuzzer_command_generator.o \ + hashtable.o \ monotonic.o \ mt19937-64.o \ release.o \ diff --git a/src/cluster_legacy.c b/src/cluster_legacy.c index ff8dc327411..8e4dde03fb9 100644 --- a/src/cluster_legacy.c +++ b/src/cluster_legacy.c @@ -236,39 +236,33 @@ static_assert(offsetof(clusterMsg, type) + sizeof(uint16_t) == RCVBUF_MIN_READ_L /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to * clusterNode structures. */ dictType clusterNodesDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* Cluster re-addition blacklist. This maps node IDs to the time * we can re-add this node. The goal is to avoid reading a removed * node for some time. */ dictType clusterNodesBlackListDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* Cluster shards hash table, mapping shard id to list of nodes */ dictType clusterSdsToListType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictListDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyListValue, }; static uint64_t dictPtrHash(const void *key) { /* We hash the pointer value itself. */ - return dictGenHashFunction(&key, sizeof(key)); + return dictGenHashFunction((const char *)&key, sizeof(key)); } static int dictPtrCompare(const void *key1, const void *key2) { @@ -278,12 +272,10 @@ static int dictPtrCompare(const void *key1, const void *key2) { /* Dictionary type for mapping hash slots to cluster nodes. * Keys are slot numbers encoded directly as pointer values, values are clusterNode pointers. */ dictType clusterSlotDictType = { - dictPtrHash, /* hash function */ - NULL, /* key dup */ - dictPtrCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictPtrHash, + .keyCompare = dictPtrCompare, + .entryDestructor = zfree, }; typedef struct { @@ -4852,7 +4844,7 @@ void clusterSendPing(clusterLink *link, int type) { int candidates_wanted = wanted + 2; /* +2 for myself and link->node */ if (candidates_wanted > (int)dictSize(server.cluster->nodes)) candidates_wanted = dictSize(server.cluster->nodes); - dictEntry **candidates = zmalloc(sizeof(dictEntry *) * candidates_wanted); + void **candidates = zmalloc(sizeof(void *) * candidates_wanted); unsigned int ncandidates = dictGetSomeKeys(server.cluster->nodes, candidates, candidates_wanted); for (unsigned int i = 0; i < ncandidates && gossipcount < wanted; i++) { diff --git a/src/config.c b/src/config.c index 93ef289e328..48ea1c46961 100644 --- a/src/config.c +++ b/src/config.c @@ -1041,21 +1041,17 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state); * like "maxmemory" -> list of line numbers (first line is zero). */ dictType optionToLineDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictListDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyListValue, }; dictType optionSetDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* The config rewrite state. */ diff --git a/src/defrag.c b/src/defrag.c index ce5e6f751d5..670f83bee73 100644 --- a/src/defrag.c +++ b/src/defrag.c @@ -299,16 +299,41 @@ static void activeDefragZsetNode(void *privdata, void *entry_ref) { #define DEFRAG_SDS_DICT_VAL_VOID_PTR 3 #define DEFRAG_SDS_DICT_VAL_LUA_SCRIPT 4 -static void activeDefragSdsDictCallback(void *privdata, const dictEntry *de) { - UNUSED(privdata); - UNUSED(de); +typedef void *(dictDefragAllocFunction)(void *ptr); +typedef struct { + dictDefragAllocFunction *defragKey; + dictDefragAllocFunction *defragVal; +} dictDefragFunctions; + +static void activeDefragDictCallback(void *privdata, void *entry_ref) { + dictDefragFunctions *defragfns = privdata; + dictEntry **de_ref = (dictEntry **)entry_ref; + dictEntry *de = *de_ref; + + /* Defrag the entry itself */ + dictEntry *newentry = activeDefragAlloc(de); + if (newentry) { + de = newentry; + *de_ref = newentry; + } + + /* Defrag the key */ + if (defragfns->defragKey) { + void *newkey = defragfns->defragKey(de->key); + if (newkey) de->key = newkey; + } + + /* Defrag the value */ + if (defragfns->defragVal) { + void *newval = defragfns->defragVal(de->v.val); + if (newval) de->v.val = newval; + } } /* Defrag a dict with sds key and optional value (either ptr, sds or robj string) */ static void activeDefragSdsDict(dict *d, int val_type) { unsigned long cursor = 0; dictDefragFunctions defragfns = { - .defragAlloc = activeDefragAlloc, .defragKey = (dictDefragAllocFunction *)activeDefragSds, .defragVal = (val_type == DEFRAG_SDS_DICT_VAL_IS_SDS ? (dictDefragAllocFunction *)activeDefragSds : val_type == DEFRAG_SDS_DICT_VAL_IS_STROB ? (dictDefragAllocFunction *)activeDefragStringOb @@ -316,7 +341,8 @@ static void activeDefragSdsDict(dict *d, int val_type) { : val_type == DEFRAG_SDS_DICT_VAL_LUA_SCRIPT ? (dictDefragAllocFunction *)evalActiveDefragScript : NULL)}; do { - cursor = dictScanDefrag(d, cursor, activeDefragSdsDictCallback, &defragfns, NULL); + cursor = hashtableScanDefrag(d, cursor, activeDefragDictCallback, + &defragfns, activeDefragAlloc, HASHTABLE_SCAN_EMIT_REF); } while (cursor != 0); } diff --git a/src/dict.c b/src/dict.c deleted file mode 100644 index e8e8d77f8b1..00000000000 --- a/src/dict.c +++ /dev/null @@ -1,1423 +0,0 @@ -/* Hash Tables Implementation. - * - * This file implements in memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) - * - * Copyright (c) 2006-2012, Redis Ltd. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/* - * Copyright (c) Valkey Contributors - * All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - */ -#include "fmacros.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dict.h" -#include "zmalloc.h" -#include "serverassert.h" -#include "monotonic.h" -#include "config.h" -#include "util.h" - -#define UNUSED(V) ((void)V) - -/* Using dictSetResizeEnabled() we make possible to disable - * resizing and rehashing of the hash table as needed. This is very important - * for us, as we use copy-on-write and don't want to move too much memory - * around when there is a child performing saving operations. - * - * Note that even when dict_can_resize is set to DICT_RESIZE_AVOID, not all - * resizes are prevented: - * - A hash table is still allowed to expand if the ratio between the number - * of elements and the buckets >= dict_force_resize_ratio. - * - A hash table is still allowed to shrink if the ratio between the number - * of elements and the buckets <= 1 / (HASHTABLE_MIN_FILL * dict_force_resize_ratio). */ -static dictResizeEnable dict_can_resize = DICT_RESIZE_ENABLE; -static unsigned int dict_force_resize_ratio = 4; - -/* -------------------------- types ----------------------------------------- */ - -struct dictEntry { - void *key; - union { - void *val; - uint64_t u64; - int64_t s64; - double d; - } v; - struct dictEntry *next; /* Next entry in the same hash bucket. */ -}; - -/* -------------------------- private prototypes ---------------------------- */ -static dictEntry **dictGetNextRef(dictEntry *de); -static void dictSetNext(dictEntry *de, dictEntry *next); - -/* -------------------------- Utility functions -------------------------------- */ -static void dictShrinkIfAutoResizeAllowed(dict *d) { - /* Automatic resizing is disallowed. Return */ - if (d->pauseAutoResize > 0) return; - - dictShrinkIfNeeded(d); -} - -/* Expand the hash table if needed */ -static void dictExpandIfAutoResizeAllowed(dict *d) { - /* Automatic resizing is disallowed. Return */ - if (d->pauseAutoResize > 0) return; - - dictExpandIfNeeded(d); -} - -/* Our hash table capability is a power of two */ -static signed char dictNextExp(unsigned long size) { - if (size <= DICT_HT_INITIAL_SIZE) return DICT_HT_INITIAL_EXP; - if (size >= LONG_MAX) return (8 * sizeof(long) - 1); - - return 8 * sizeof(long) - __builtin_clzl(size - 1); -} - -/* This function performs just a step of rehashing, and only if hashing has - * not been paused for our hash table. When we have iterators in the - * middle of a rehashing we can't mess with the two hash tables otherwise - * some elements can be missed or duplicated. - * - * This function is called by common lookup or update operations in the - * dictionary so that the hash table automatically migrates from H1 to H2 - * while it is actively used. */ -static void dictRehashStep(dict *d) { - if (d->pauserehash == 0) dictRehash(d, 1); -} - -/* -------------------------- hash functions -------------------------------- */ - -static uint8_t dict_hash_function_seed[16]; - -void dictSetHashFunctionSeed(uint8_t *seed) { - memcpy(dict_hash_function_seed, seed, sizeof(dict_hash_function_seed)); -} - -uint8_t *dictGetHashFunctionSeed(void) { - return dict_hash_function_seed; -} - -/* The default hashing function uses SipHash implementation - * in siphash.c. */ - -uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k); -uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k); - -uint64_t dictGenHashFunction(const void *key, size_t len) { - return siphash(key, len, dict_hash_function_seed); -} - -uint64_t dictGenCaseHashFunction(const unsigned char *buf, size_t len) { - return siphash_nocase(buf, len, dict_hash_function_seed); -} - -static inline dictEntry *createEntry(void *key, dictEntry *next) { - dictEntry *entry = zmalloc(sizeof(dictEntry)); - entry->key = key; - entry->next = next; - return entry; -} - -/* ----------------------------- API implementation ------------------------- */ - -/* Reset hash table parameters already initialized with dictInit()*/ -static void dictReset(dict *d, int htidx) { - d->ht_table[htidx] = NULL; - d->ht_size_exp[htidx] = -1; - d->ht_used[htidx] = 0; -} - -/* Initialize the hash table */ -static int dictInit(dict *d, dictType *type) { - dictReset(d, 0); - dictReset(d, 1); - d->type = type; - d->rehashidx = -1; - d->pauserehash = 0; - d->pauseAutoResize = 0; - return DICT_OK; -} - -/* Create a new hash table */ -dict *dictCreate(dictType *type) { - size_t metasize = type->dictMetadataBytes ? type->dictMetadataBytes(NULL) : 0; - dict *d = zmalloc(sizeof(*d) + metasize); - if (metasize > 0) { - memset(dictMetadata(d), 0, metasize); - } - dictInit(d, type); - return d; -} - -/* Resize or create the hash table, - * when malloc_failed is non-NULL, it'll avoid panic if malloc fails (in which case it'll be set to 1). - * Returns DICT_OK if resize was performed, and DICT_ERR if skipped. */ -static int dictResizeWithOptionalCheck(dict *d, unsigned long size, int *malloc_failed) { - if (malloc_failed) *malloc_failed = 0; - - /* We can't rehash twice if rehashing is ongoing. */ - assert(!dictIsRehashing(d)); - - /* the new hash table */ - dictEntry **new_ht_table; - unsigned long new_ht_used; - signed char new_ht_size_exp = dictNextExp(size); - - /* Detect overflows */ - size_t newsize = DICTHT_SIZE(new_ht_size_exp); - if (newsize < size || newsize * sizeof(dictEntry *) < newsize) return DICT_ERR; - - /* Rehashing to the same table size is not useful. */ - if (new_ht_size_exp == d->ht_size_exp[0]) return DICT_ERR; - - /* Allocate the new hash table and initialize all pointers to NULL */ - if (malloc_failed) { - new_ht_table = ztrycalloc(newsize * sizeof(dictEntry *)); - *malloc_failed = new_ht_table == NULL; - if (*malloc_failed) return DICT_ERR; - } else { - new_ht_table = zcalloc(newsize * sizeof(dictEntry *)); - } - - new_ht_used = 0; - - /* Prepare a second hash table for incremental rehashing. - * We do this even for the first initialization, so that we can trigger the - * rehashingStarted more conveniently, we will clean it up right after. */ - d->ht_size_exp[1] = new_ht_size_exp; - d->ht_used[1] = new_ht_used; - d->ht_table[1] = new_ht_table; - d->rehashidx = 0; - if (d->type->rehashingStarted) d->type->rehashingStarted(d); - - /* Is this the first initialization or is the first hash table empty? If so - * it's not really a rehashing, we can just set the first hash table so that - * it can accept keys. */ - if (d->ht_table[0] == NULL || d->ht_used[0] == 0) { - if (d->type->rehashingCompleted) d->type->rehashingCompleted(d); - if (d->ht_table[0]) zfree(d->ht_table[0]); - d->ht_size_exp[0] = new_ht_size_exp; - d->ht_used[0] = new_ht_used; - d->ht_table[0] = new_ht_table; - dictReset(d, 1); - d->rehashidx = -1; - return DICT_OK; - } - - return DICT_OK; -} - -static int dictExpandWithOptionalCheck(dict *d, unsigned long size, int *malloc_failed) { - /* the size is invalid if it is smaller than the size of the hash table - * or smaller than the number of elements already inside the hash table */ - if (dictIsRehashing(d) || d->ht_used[0] > size || DICTHT_SIZE(d->ht_size_exp[0]) >= size) return DICT_ERR; - return dictResizeWithOptionalCheck(d, size, malloc_failed); -} - -/* return DICT_ERR if expand was not performed */ -int dictExpand(dict *d, unsigned long size) { - return dictExpandWithOptionalCheck(d, size, NULL); -} - -/* return DICT_ERR if expand failed due to memory allocation failure */ -int dictTryExpand(dict *d, unsigned long size) { - int malloc_failed = 0; - dictExpandWithOptionalCheck(d, size, &malloc_failed); - return malloc_failed ? DICT_ERR : DICT_OK; -} - -/* return DICT_ERR if shrink was not performed */ -int dictShrink(dict *d, unsigned long size) { - /* the size is invalid if it is bigger than the size of the hash table - * or smaller than the number of elements already inside the hash table */ - if (dictIsRehashing(d) || d->ht_used[0] > size || DICTHT_SIZE(d->ht_size_exp[0]) <= size) return DICT_ERR; - return dictResizeWithOptionalCheck(d, size, NULL); -} - -/* Helper function for `dictRehash` and `dictBucketRehash` which rehashes all the keys - * in a bucket at index `idx` from the old to the new hash HT. */ -static void rehashEntriesInBucketAtIndex(dict *d, uint64_t idx) { - dictEntry *de = d->ht_table[0][idx]; - uint64_t h; - dictEntry *nextde; - while (de) { - nextde = dictGetNext(de); - void *key = dictGetKey(de); - /* Get the index in the new hash table */ - if (d->ht_size_exp[1] > d->ht_size_exp[0]) { - h = dictHashKey(d, key) & DICTHT_SIZE_MASK(d->ht_size_exp[1]); - } else { - /* We're shrinking the table. The tables sizes are powers of - * two, so we simply mask the bucket index in the larger table - * to get the bucket index in the smaller table. */ - h = idx & DICTHT_SIZE_MASK(d->ht_size_exp[1]); - } - dictSetNext(de, d->ht_table[1][h]); - d->ht_table[1][h] = de; - d->ht_used[0]--; - d->ht_used[1]++; - de = nextde; - } - d->ht_table[0][idx] = NULL; -} - -/* This checks if we already rehashed the whole table and if more rehashing is required */ -static int dictCheckRehashingCompleted(dict *d) { - if (d->ht_used[0] != 0) return 0; - - if (d->type->rehashingCompleted) d->type->rehashingCompleted(d); - zfree(d->ht_table[0]); - /* Copy the new ht onto the old one */ - d->ht_table[0] = d->ht_table[1]; - d->ht_used[0] = d->ht_used[1]; - d->ht_size_exp[0] = d->ht_size_exp[1]; - dictReset(d, 1); - d->rehashidx = -1; - return 1; -} - -/* Performs N steps of incremental rehashing. Returns 1 if there are still - * keys to move from the old to the new hash table, otherwise 0 is returned. - * - * Note that a rehashing step consists in moving a bucket (that may have more - * than one key as we use chaining) from the old to the new hash table, however - * since part of the hash table may be composed of empty spaces, it is not - * guaranteed that this function will rehash even a single bucket, since it - * will visit at max N*10 empty buckets in total, otherwise the amount of - * work it does would be unbound and the function may block for a long time. */ -int dictRehash(dict *d, int n) { - int empty_visits = n * 10; /* Max number of empty buckets to visit. */ - unsigned long s0 = DICTHT_SIZE(d->ht_size_exp[0]); - unsigned long s1 = DICTHT_SIZE(d->ht_size_exp[1]); - if (dict_can_resize == DICT_RESIZE_FORBID || !dictIsRehashing(d)) return 0; - /* If dict_can_resize is DICT_RESIZE_AVOID, we want to avoid rehashing. - * - If expanding, the threshold is dict_force_resize_ratio which is 4. - * - If shrinking, the threshold is 1 / (HASHTABLE_MIN_FILL * dict_force_resize_ratio) which is 1/32. */ - if (dict_can_resize == DICT_RESIZE_AVOID && ((s1 > s0 && s1 < dict_force_resize_ratio * s0) || - (s1 < s0 && s0 < HASHTABLE_MIN_FILL * dict_force_resize_ratio * s1))) { - return 0; - } - - while (n-- && d->ht_used[0] != 0) { - /* Note that rehashidx can't overflow as we are sure there are more - * elements because ht[0].used != 0 */ - assert(DICTHT_SIZE(d->ht_size_exp[0]) > (unsigned long)d->rehashidx); - while (d->ht_table[0][d->rehashidx] == NULL) { - d->rehashidx++; - if (--empty_visits == 0) return 1; - } - /* Move all the keys in this bucket from the old to the new hash HT */ - rehashEntriesInBucketAtIndex(d, d->rehashidx); - d->rehashidx++; - } - - return !dictCheckRehashingCompleted(d); -} - -long long timeInMilliseconds(void) { - struct timeval tv; - - gettimeofday(&tv, NULL); - return (((long long)tv.tv_sec) * 1000) + (tv.tv_usec / 1000); -} - -/* Rehash in us+"delta" microseconds. The value of "delta" is larger - * than 0, and is smaller than 1000 in most cases. The exact upper bound - * depends on the running time of dictRehash(d,100).*/ -int dictRehashMicroseconds(dict *d, uint64_t us) { - if (d->pauserehash > 0) return 0; - - monotime timer; - elapsedStart(&timer); - int rehashes = 0; - - while (dictRehash(d, 100)) { - rehashes += 100; - if (elapsedUs(timer) >= us) break; - } - return rehashes; -} - -/* Performs rehashing on a single bucket. */ -static int dictBucketRehash(dict *d, uint64_t idx) { - if (d->pauserehash != 0) return 0; - unsigned long s0 = DICTHT_SIZE(d->ht_size_exp[0]); - unsigned long s1 = DICTHT_SIZE(d->ht_size_exp[1]); - if (dict_can_resize == DICT_RESIZE_FORBID || !dictIsRehashing(d)) return 0; - /* If dict_can_resize is DICT_RESIZE_AVOID, we want to avoid rehashing. - * - If expanding, the threshold is dict_force_resize_ratio which is 4. - * - If shrinking, the threshold is 1 / (HASHTABLE_MIN_FILL * dict_force_resize_ratio) which is 1/32. */ - if (dict_can_resize == DICT_RESIZE_AVOID && ((s1 > s0 && s1 < dict_force_resize_ratio * s0) || - (s1 < s0 && s0 < HASHTABLE_MIN_FILL * dict_force_resize_ratio * s1))) { - return 0; - } - rehashEntriesInBucketAtIndex(d, idx); - dictCheckRehashingCompleted(d); - return 1; -} - -/* Add an element to the target hash table */ -int dictAdd(dict *d, void *key, void *val) { - dictEntry *entry = dictAddRaw(d, key, NULL); - - if (!entry) return DICT_ERR; - dictSetVal(d, entry, val); - return DICT_OK; -} - -/* Low level add or find: - * This function adds the entry but instead of setting a value returns the - * dictEntry structure to the user, that will make sure to fill the value - * field as they wish. - * - * This function is also directly exposed to the user API to be called - * mainly in order to store non-pointers inside the hash value, example: - * - * entry = dictAddRaw(dict,mykey,NULL); - * if (entry != NULL) dictSetSignedIntegerVal(entry,1000); - * - * Return values: - * - * If key already exists NULL is returned, and "*existing" is populated - * with the existing entry if existing is not NULL. - * - * If key was added, the hash entry is returned to be manipulated by the caller. - * - * The dict handles `key` based on `dictType` during initialization: - * - If `dictType.embedded-entry` is 1, it clones the `key`. - * - Otherwise, it assumes ownership of the `key`. - */ -dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing) { - /* Get the position for the new key or NULL if the key already exists. */ - void *position = dictFindPositionForInsert(d, key, existing); - if (!position) return NULL; - - /* Dup the key if necessary. */ - if (d->type->keyDup) key = d->type->keyDup(key); - - return dictInsertAtPosition(d, key, position); -} - -/* Adds a key in the dict's hashtable at the position returned by a preceding - * call to dictFindPositionForInsert. This is a low level function which allows - * splitting dictAddRaw in two parts. Normally, dictAddRaw or dictAdd should be - * used instead. */ -dictEntry *dictInsertAtPosition(dict *d, void *key, void *position) { - dictEntry **bucket = position; /* It's a bucket, but the API hides that. */ - dictEntry *entry; - /* If rehashing is ongoing, we insert in table 1, otherwise in table 0. - * Assert that the provided bucket is the right table. */ - int htidx = dictIsRehashing(d) ? 1 : 0; - assert(bucket >= &d->ht_table[htidx][0] && bucket <= &d->ht_table[htidx][DICTHT_SIZE_MASK(d->ht_size_exp[htidx])]); - /* Allocate the memory and store the new entry. - * Insert the element in top, with the assumption that in a database - * system it is more likely that recently added entries are accessed - * more frequently. */ - entry = createEntry(key, *bucket); - *bucket = entry; - d->ht_used[htidx]++; - - return entry; -} - -/* Add or Overwrite: - * Add an element, discarding the old value if the key already exists. - * Return 1 if the key was added from scratch, 0 if there was already an - * element with such key and dictReplace() just performed a value update - * operation. */ -int dictReplace(dict *d, void *key, void *val) { - dictEntry *entry, *existing; - - /* Try to add the element. If the key - * does not exists dictAdd will succeed. */ - entry = dictAddRaw(d, key, &existing); - if (entry) { - dictSetVal(d, entry, val); - return 1; - } - - /* Set the new value and free the old one. Note that it is important - * to do that in this order, as the value may just be exactly the same - * as the previous one. In this context, think to reference counting, - * you want to increment (set), and then decrement (free), and not the - * reverse. */ - void *oldval = dictGetVal(existing); - dictSetVal(d, existing, val); - if (d->type->valDestructor) d->type->valDestructor(oldval); - return 0; -} - -/* Add or Find: - * dictAddOrFind() is simply a version of dictAddRaw() that always - * returns the hash entry of the specified key, even if the key already - * exists and can't be added (in that case the entry of the already - * existing key is returned.) - * - * See dictAddRaw() for more information. */ -dictEntry *dictAddOrFind(dict *d, void *key) { - dictEntry *entry, *existing; - entry = dictAddRaw(d, key, &existing); - return entry ? entry : existing; -} - -/* Search and remove an element. This is a helper function for - * dictDelete() and dictUnlink(), please check the top comment - * of those functions. */ -static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) { - uint64_t h, idx; - dictEntry *he, *prevHe; - int table; - - /* dict is empty */ - if (dictSize(d) == 0) return NULL; - - h = dictHashKey(d, key); - idx = h & DICTHT_SIZE_MASK(d->ht_size_exp[0]); - - if (dictIsRehashing(d)) { - if ((long)idx >= d->rehashidx && d->ht_table[0][idx]) { - /* If we have a valid hash entry at `idx` in ht0, we perform - * rehash on the bucket at `idx` (being more CPU cache friendly) */ - dictBucketRehash(d, idx); - } else { - /* If the hash entry is not in ht0, we rehash the buckets based - * on the rehashidx (not CPU cache friendly). */ - dictRehashStep(d); - } - } - - for (table = 0; table <= 1; table++) { - if (table == 0 && (long)idx < d->rehashidx) continue; - idx = h & DICTHT_SIZE_MASK(d->ht_size_exp[table]); - he = d->ht_table[table][idx]; - prevHe = NULL; - while (he) { - void *he_key = dictGetKey(he); - if (key == he_key || dictCompareKeys(d, key, he_key)) { - /* Unlink the element from the list */ - if (prevHe) - dictSetNext(prevHe, dictGetNext(he)); - else - d->ht_table[table][idx] = dictGetNext(he); - if (!nofree) { - dictFreeUnlinkedEntry(d, he); - } - d->ht_used[table]--; - dictShrinkIfAutoResizeAllowed(d); - return he; - } - prevHe = he; - he = dictGetNext(he); - } - if (!dictIsRehashing(d)) break; - } - return NULL; /* not found */ -} - -/* Remove an element, returning DICT_OK on success or DICT_ERR if the - * element was not found. */ -int dictDelete(dict *ht, const void *key) { - return dictGenericDelete(ht, key, 0) ? DICT_OK : DICT_ERR; -} - -/* Remove an element from the table, but without actually releasing - * the key, value and dictionary entry. The dictionary entry is returned - * if the element was found (and unlinked from the table), and the user - * should later call `dictFreeUnlinkedEntry()` with it in order to release it. - * Otherwise if the key is not found, NULL is returned. - * - * This function is useful when we want to remove something from the hash - * table but want to use its value before actually deleting the entry. - * Without this function the pattern would require two lookups: - * - * entry = dictFind(...); - * // Do something with entry - * dictDelete(dictionary,entry); - * - * Thanks to this function it is possible to avoid this, and use - * instead: - * - * entry = dictUnlink(dictionary,entry); - * // Do something with entry - * dictFreeUnlinkedEntry(entry); // <- This does not need to lookup again. - */ -dictEntry *dictUnlink(dict *d, const void *key) { - return dictGenericDelete(d, key, 1); -} - -inline static void dictFreeKey(dict *d, dictEntry *entry) { - if (d->type->keyDestructor) { - d->type->keyDestructor(dictGetKey(entry)); - } -} - -inline static void dictFreeVal(dict *d, dictEntry *entry) { - if (d->type->valDestructor) { - d->type->valDestructor(dictGetVal(entry)); - } -} - -/* You need to call this function to really free the entry after a call - * to dictUnlink(). It's safe to call this function with 'he' = NULL. */ -void dictFreeUnlinkedEntry(dict *d, dictEntry *he) { - if (he == NULL) return; - dictFreeKey(d, he); - dictFreeVal(d, he); - /* Clear the dictEntry */ - zfree(he); -} - -/* Destroy an entire dictionary */ -static int dictClear(dict *d, int htidx, void(callback)(dict *)) { - unsigned long i; - - /* Free all the elements */ - for (i = 0; i < DICTHT_SIZE(d->ht_size_exp[htidx]) && d->ht_used[htidx] > 0; i++) { - dictEntry *he, *nextHe; - - if (callback && (i & 65535) == 0) callback(d); - - if ((he = d->ht_table[htidx][i]) == NULL) continue; - while (he) { - nextHe = dictGetNext(he); - dictFreeKey(d, he); - dictFreeVal(d, he); - zfree(he); - d->ht_used[htidx]--; - he = nextHe; - } - } - /* Free the table and the allocated cache structure */ - zfree(d->ht_table[htidx]); - /* Re-initialize the table */ - dictReset(d, htidx); - return DICT_OK; /* never fails */ -} - -/* Clear & Release the hash table */ -void dictRelease(dict *d) { - /* Someone may be monitoring a dict that started rehashing, before - * destroying the dict fake completion. */ - if (dictIsRehashing(d) && d->type->rehashingCompleted) d->type->rehashingCompleted(d); - dictClear(d, 0, NULL); - dictClear(d, 1, NULL); - zfree(d); -} - -dictEntry *dictFind(dict *d, const void *key) { - dictEntry *he; - uint64_t h, idx, table; - - if (dictSize(d) == 0) return NULL; /* dict is empty */ - - h = dictHashKey(d, key); - idx = h & DICTHT_SIZE_MASK(d->ht_size_exp[0]); - - if (dictIsRehashing(d)) { - if ((long)idx >= d->rehashidx && d->ht_table[0][idx]) { - /* If we have a valid hash entry at `idx` in ht0, we perform - * rehash on the bucket at `idx` (being more CPU cache friendly) */ - dictBucketRehash(d, idx); - } else { - /* If the hash entry is not in ht0, we rehash the buckets based - * on the rehashidx (not CPU cache friendly). */ - dictRehashStep(d); - } - } - - for (table = 0; table <= 1; table++) { - if (table == 0 && (long)idx < d->rehashidx) continue; - idx = h & DICTHT_SIZE_MASK(d->ht_size_exp[table]); - he = d->ht_table[table][idx]; - while (he) { - void *he_key = dictGetKey(he); - if (key == he_key || dictCompareKeys(d, key, he_key)) return he; - he = dictGetNext(he); - } - if (!dictIsRehashing(d)) return NULL; - } - return NULL; -} - -void *dictFetchValue(dict *d, const void *key) { - dictEntry *he; - - he = dictFind(d, key); - return he ? dictGetVal(he) : NULL; -} - -void dictSetKey(dict *d, dictEntry *de, void *key) { - void *k = d->type->keyDup ? d->type->keyDup(key) : key; - de->key = k; -} - -void dictSetVal(dict *d, dictEntry *de, void *val) { - UNUSED(d); - de->v.val = val; -} - -void dictSetSignedIntegerVal(dictEntry *de, int64_t val) { - de->v.s64 = val; -} - -void dictSetUnsignedIntegerVal(dictEntry *de, uint64_t val) { - de->v.u64 = val; -} - -void dictSetDoubleVal(dictEntry *de, double val) { - de->v.d = val; -} - -int64_t dictIncrSignedIntegerVal(dictEntry *de, int64_t val) { - de->v.s64 += val; - return de->v.s64; -} - -uint64_t dictIncrUnsignedIntegerVal(dictEntry *de, uint64_t val) { - de->v.u64 += val; - return de->v.u64; -} - -double dictIncrDoubleVal(dictEntry *de, double val) { - de->v.d += val; - return de->v.d; -} - -void *dictGetKey(const dictEntry *de) { - return de->key; -} - -void *dictGetVal(const dictEntry *de) { - return de->v.val; -} - -int64_t dictGetSignedIntegerVal(const dictEntry *de) { - return de->v.s64; -} - -uint64_t dictGetUnsignedIntegerVal(const dictEntry *de) { - return de->v.u64; -} - -double dictGetDoubleVal(const dictEntry *de) { - return de->v.d; -} - -/* Returns a mutable reference to the value as a double within the entry. */ -double *dictGetDoubleValPtr(dictEntry *de) { - return &de->v.d; -} - -/* Returns the 'next' field of the entry or NULL if the entry doesn't have a - * 'next' field. */ -dictEntry *dictGetNext(const dictEntry *de) { - return de->next; -} - -/* Returns a pointer to the 'next' field in the entry or NULL if the entry - * doesn't have a next field. */ -static dictEntry **dictGetNextRef(dictEntry *de) { - return &de->next; -} - -static void dictSetNext(dictEntry *de, dictEntry *next) { - de->next = next; -} - -/* Returns the memory usage in bytes of the dict, excluding the size of the keys - * and values. */ -size_t dictMemUsage(const dict *d) { - return dictSize(d) * sizeof(dictEntry) + dictBuckets(d) * sizeof(dictEntry *); -} - -/* Returns the memory usage in bytes of dictEntry based on the type. if `de` is NULL, return the size of - * regular dict entry else return based on the type. */ -size_t dictEntryMemUsage(dictEntry *de) { - return sizeof(*de); -} - -/* A fingerprint is a 64 bit number that represents the state of the dictionary - * at a given time, it's just a few dict properties xored together. - * When an unsafe iterator is initialized, we get the dict fingerprint, and check - * the fingerprint again when the iterator is released. - * If the two fingerprints are different it means that the user of the iterator - * performed forbidden operations against the dictionary while iterating. */ -unsigned long long dictFingerprint(dict *d) { - unsigned long long integers[6], hash = 0; - int j; - - integers[0] = (long)d->ht_table[0]; - integers[1] = d->ht_size_exp[0]; - integers[2] = d->ht_used[0]; - integers[3] = (long)d->ht_table[1]; - integers[4] = d->ht_size_exp[1]; - integers[5] = d->ht_used[1]; - - /* We hash N integers by summing every successive integer with the integer - * hashing of the previous sum. Basically: - * - * Result = hash(hash(hash(int1)+int2)+int3) ... - * - * This way the same set of integers in a different order will (likely) hash - * to a different number. */ - for (j = 0; j < 6; j++) { - hash += integers[j]; - hash = wangHash64(hash); - } - return hash; -} - -/* Initialize a normal iterator. This function should be called when initializing - * an iterator on the stack. */ -void dictInitIterator(dictIterator *iter, dict *d) { - iter->d = d; - iter->table = 0; - iter->index = -1; - iter->safe = 0; - iter->entry = NULL; - iter->nextEntry = NULL; -} - -/* Initialize a safe iterator, which is allowed to modify the dictionary while iterating. - * You must call dictResetIterator when you are done with a safe iterator. */ -void dictInitSafeIterator(dictIterator *iter, dict *d) { - dictInitIterator(iter, d); - iter->safe = 1; -} - -void dictResetIterator(dictIterator *iter) { - if (!(iter->index == -1 && iter->table == 0)) { - if (iter->safe) { - dictResumeRehashing(iter->d); - assert(iter->d->pauserehash >= 0); - } else - assert(iter->fingerprint == dictFingerprint(iter->d)); - } -} - -dictIterator *dictGetIterator(dict *d) { - dictIterator *iter = zmalloc(sizeof(*iter)); - dictInitIterator(iter, d); - return iter; -} - -dictIterator *dictGetSafeIterator(dict *d) { - dictIterator *i = dictGetIterator(d); - - i->safe = 1; - return i; -} - -dictEntry *dictNext(dictIterator *iter) { - while (1) { - if (iter->entry == NULL) { - if (iter->index == -1 && iter->table == 0) { - if (iter->safe) - dictPauseRehashing(iter->d); - else - iter->fingerprint = dictFingerprint(iter->d); - - /* skip the rehashed slots in table[0] */ - if (dictIsRehashing(iter->d)) { - iter->index = iter->d->rehashidx - 1; - } - } - iter->index++; - if (iter->index >= (long)DICTHT_SIZE(iter->d->ht_size_exp[iter->table])) { - if (dictIsRehashing(iter->d) && iter->table == 0) { - iter->table++; - iter->index = 0; - } else { - break; - } - } - iter->entry = iter->d->ht_table[iter->table][iter->index]; - } else { - iter->entry = iter->nextEntry; - } - if (iter->entry) { - /* We need to save the 'next' here, the iterator user - * may delete the entry we are returning. */ - iter->nextEntry = dictGetNext(iter->entry); - return iter->entry; - } - } - return NULL; -} - -void dictReleaseIterator(dictIterator *iter) { - dictResetIterator(iter); - zfree(iter); -} - -/* Return a random entry from the hash table. Useful to - * implement randomized algorithms */ -dictEntry *dictGetRandomKey(dict *d) { - dictEntry *he, *orighe; - unsigned long h; - int listlen, listele; - - if (dictSize(d) == 0) return NULL; - if (dictIsRehashing(d)) dictRehashStep(d); - if (dictIsRehashing(d)) { - unsigned long s0 = DICTHT_SIZE(d->ht_size_exp[0]); - do { - /* We are sure there are no elements in indexes from 0 - * to rehashidx-1 */ - h = d->rehashidx + (randomULong() % (dictBuckets(d) - d->rehashidx)); - he = (h >= s0) ? d->ht_table[1][h - s0] : d->ht_table[0][h]; - } while (he == NULL); - } else { - unsigned long m = DICTHT_SIZE_MASK(d->ht_size_exp[0]); - do { - h = randomULong() & m; - he = d->ht_table[0][h]; - } while (he == NULL); - } - - /* Now we found a non empty bucket, but it is a linked - * list and we need to get a random element from the list. - * The only sane way to do so is counting the elements and - * select a random index. */ - listlen = 0; - orighe = he; - while (he) { - he = dictGetNext(he); - listlen++; - } - listele = random() % listlen; - he = orighe; - while (listele--) he = dictGetNext(he); - return he; -} - -/* This function samples the dictionary to return a few keys from random - * locations. - * - * It neither guarantees it will return all the keys specified in 'count', nor - * does it guarantee to return non-duplicated elements, however it will make - * some effort to do both things. - * - * Returned pointers to hash table entries are stored into 'des' that - * points to an array of dictEntry pointers. The array must have room for - * at least 'count' elements, that is the argument we pass to the function - * to tell how many random elements we need. - * - * The function returns the number of items stored into 'des', that may - * be less than 'count' if the hash table has less than 'count' elements - * inside, or if not enough elements were found in a reasonable amount of - * steps. - * - * Note that this function is not suitable when you need a good distribution - * of the returned items, but only when you need to "sample" a given number - * of continuous elements to run some kind of algorithm or to produce - * statistics. However the function is much faster than dictGetRandomKey() - * at producing N elements. */ -unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) { - unsigned long j; /* internal hash table id, 0 or 1. */ - unsigned long tables; /* 1 or 2 tables? */ - unsigned long stored = 0, maxsizemask; - unsigned long maxsteps; - - if (dictSize(d) < count) count = dictSize(d); - maxsteps = count * 10; - - /* Try to do a rehashing work proportional to 'count'. */ - for (j = 0; j < count; j++) { - if (dictIsRehashing(d)) - dictRehashStep(d); - else - break; - } - - tables = dictIsRehashing(d) ? 2 : 1; - maxsizemask = DICTHT_SIZE_MASK(d->ht_size_exp[0]); - if (tables > 1 && maxsizemask < DICTHT_SIZE_MASK(d->ht_size_exp[1])) - maxsizemask = DICTHT_SIZE_MASK(d->ht_size_exp[1]); - - /* Pick a random point inside the larger table. */ - unsigned long i = randomULong() & maxsizemask; - unsigned long emptylen = 0; /* Continuous empty entries so far. */ - while (stored < count && maxsteps--) { - for (j = 0; j < tables; j++) { - /* Invariant of the dict.c rehashing: up to the indexes already - * visited in ht[0] during the rehashing, there are no populated - * buckets, so we can skip ht[0] for indexes between 0 and idx-1. */ - if (tables == 2 && j == 0 && i < (unsigned long)d->rehashidx) { - /* Moreover, if we are currently out of range in the second - * table, there will be no elements in both tables up to - * the current rehashing index, so we jump if possible. - * (this happens when going from big to small table). */ - if (i >= DICTHT_SIZE(d->ht_size_exp[1])) - i = d->rehashidx; - else - continue; - } - if (i >= DICTHT_SIZE(d->ht_size_exp[j])) continue; /* Out of range for this table. */ - dictEntry *he = d->ht_table[j][i]; - - /* Count contiguous empty buckets, and jump to other - * locations if they reach 'count' (with a minimum of 5). */ - if (he == NULL) { - emptylen++; - if (emptylen >= 5 && emptylen > count) { - i = randomULong() & maxsizemask; - emptylen = 0; - } - } else { - emptylen = 0; - while (he) { - /* Collect all the elements of the buckets found non empty while iterating. - * To avoid the issue of being unable to sample the end of a long chain, - * we utilize the Reservoir Sampling algorithm to optimize the sampling process. - * This means that even when the maximum number of samples has been reached, - * we continue sampling until we reach the end of the chain. - * See https://en.wikipedia.org/wiki/Reservoir_sampling. */ - if (stored < count) { - des[stored] = he; - } else { - unsigned long r = randomULong() % (stored + 1); - if (r < count) des[r] = he; - } - - he = dictGetNext(he); - stored++; - } - if (stored >= count) goto end; - } - } - i = (i + 1) & maxsizemask; - } - -end: - return stored > count ? count : stored; -} - - -/* Reallocate the dictEntry, key and value allocations in a bucket using the - * provided allocation functions in order to defrag them. */ -static void dictDefragBucket(dictEntry **bucketref, const dictDefragFunctions *defragfns) { - dictDefragAllocFunction *defragalloc = defragfns->defragAlloc; - dictDefragAllocFunction *defragkey = defragfns->defragKey; - dictDefragAllocFunction *defragval = defragfns->defragVal; - while (bucketref && *bucketref) { - dictEntry *de = *bucketref, *newde = NULL; - void *newkey = defragkey ? defragkey(dictGetKey(de)) : NULL; - void *newval = defragval ? defragval(dictGetVal(de)) : NULL; - newde = defragalloc(de); - if (newde) de = newde; - if (newkey) de->key = newkey; - if (newval) de->v.val = newval; - if (newde) { - *bucketref = newde; - } - bucketref = dictGetNextRef(*bucketref); - } -} - -/* This is like dictGetRandomKey() from the POV of the API, but will do more - * work to ensure a better distribution of the returned element. - * - * This function improves the distribution because the dictGetRandomKey() - * problem is that it selects a random bucket, then it selects a random - * element from the chain in the bucket. However elements being in different - * chain lengths will have different probabilities of being reported. With - * this function instead what we do is to consider a "linear" range of the table - * that may be constituted of N buckets with chains of different lengths - * appearing one after the other. Then we report a random element in the range. - * In this way we smooth away the problem of different chain lengths. */ -#define GETFAIR_NUM_ENTRIES 15 -dictEntry *dictGetFairRandomKey(dict *d) { - dictEntry *entries[GETFAIR_NUM_ENTRIES]; - unsigned int count = dictGetSomeKeys(d, entries, GETFAIR_NUM_ENTRIES); - /* Note that dictGetSomeKeys() may return zero elements in an unlucky - * run() even if there are actually elements inside the hash table. So - * when we get zero, we call the true dictGetRandomKey() that will always - * yield the element if the hash table has at least one. */ - if (count == 0) return dictGetRandomKey(d); - unsigned int idx = rand() % count; - return entries[idx]; -} - -/* Function to reverse bits. Algorithm from: - * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */ -static unsigned long rev(unsigned long v) { - unsigned long s = CHAR_BIT * sizeof(v); // bit size; must be power of 2 - unsigned long mask = ~0UL; - while ((s >>= 1) > 0) { - mask ^= (mask << s); - v = ((v >> s) & mask) | ((v << s) & ~mask); - } - return v; -} - -/* dictScan() is used to iterate over the elements of a dictionary. - * - * Iterating works the following way: - * - * 1) Initially you call the function using a cursor (v) value of 0. - * 2) The function performs one step of the iteration, and returns the - * new cursor value you must use in the next call. - * 3) When the returned cursor is 0, the iteration is complete. - * - * The function guarantees all elements present in the - * dictionary get returned between the start and end of the iteration. - * However it is possible some elements get returned multiple times. - * - * For every element returned, the callback argument 'fn' is - * called with 'privdata' as first argument and the dictionary entry - * 'de' as second argument. - * - * HOW IT WORKS. - * - * The iteration algorithm was designed by Pieter Noordhuis. - * The main idea is to increment a cursor starting from the higher order - * bits. That is, instead of incrementing the cursor normally, the bits - * of the cursor are reversed, then the cursor is incremented, and finally - * the bits are reversed again. - * - * This strategy is needed because the hash table may be resized between - * iteration calls. - * - * dict.c hash tables are always power of two in size, and they - * use chaining, so the position of an element in a given table is given - * by computing the bitwise AND between Hash(key) and SIZE-1 - * (where SIZE-1 is always the mask that is equivalent to taking the rest - * of the division between the Hash of the key and SIZE). - * - * For example if the current hash table size is 16, the mask is - * (in binary) 1111. The position of a key in the hash table will always be - * the last four bits of the hash output, and so forth. - * - * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE? - * - * If the hash table grows, elements can go anywhere in one multiple of - * the old bucket: for example let's say we already iterated with - * a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16). - * - * If the hash table will be resized to 64 elements, then the new mask will - * be 111111. The new buckets you obtain by substituting in ??1100 - * with either 0 or 1 can be targeted only by keys we already visited - * when scanning the bucket 1100 in the smaller hash table. - * - * By iterating the higher bits first, because of the inverted counter, the - * cursor does not need to restart if the table size gets bigger. It will - * continue iterating using cursors without '1100' at the end, and also - * without any other combination of the final 4 bits already explored. - * - * Similarly when the table size shrinks over time, for example going from - * 16 to 8, if a combination of the lower three bits (the mask for size 8 - * is 111) were already completely explored, it would not be visited again - * because we are sure we tried, for example, both 0111 and 1111 (all the - * variations of the higher bit) so we don't need to test it again. - * - * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING! - * - * Yes, this is true, but we always iterate the smaller table first, then - * we test all the expansions of the current cursor into the larger - * table. For example if the current cursor is 101 and we also have a - * larger table of size 16, we also test (0)101 and (1)101 inside the larger - * table. This reduces the problem back to having only one table, where - * the larger one, if it exists, is just an expansion of the smaller one. - * - * LIMITATIONS - * - * This iterator is completely stateless, and this is a huge advantage, - * including no additional memory used. - * - * The disadvantages resulting from this design are: - * - * 1) It is possible we return elements more than once. However this is usually - * easy to deal with in the application level. - * 2) The iterator must return multiple elements per call, as it needs to always - * return all the keys chained in a given bucket, and all the expansions, so - * we are sure we don't miss keys moving during rehashing. - * 3) The reverse cursor is somewhat hard to understand at first, but this - * comment is supposed to help. - */ -unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, void *privdata) { - return dictScanDefrag(d, v, fn, NULL, privdata); -} - -/* Like dictScan, but additionally reallocates the memory used by the dict - * entries using the provided allocation function. This feature was added for - * the active defrag feature. - * - * The 'defragfns' callbacks are called with a pointer to memory that callback - * can reallocate. The callbacks should return a new memory address or NULL, - * where NULL means that no reallocation happened and the old memory is still - * valid. */ -unsigned long -dictScanDefrag(dict *d, unsigned long v, dictScanFunction *fn, const dictDefragFunctions *defragfns, void *privdata) { - int htidx0, htidx1; - const dictEntry *de, *next; - unsigned long m0, m1; - - if (dictSize(d) == 0) return 0; - - /* This is needed in case the scan callback tries to do dictFind or alike. */ - dictPauseRehashing(d); - - if (!dictIsRehashing(d)) { - htidx0 = 0; - m0 = DICTHT_SIZE_MASK(d->ht_size_exp[htidx0]); - - /* Emit entries at cursor */ - if (defragfns) { - dictDefragBucket(&d->ht_table[htidx0][v & m0], defragfns); - } - de = d->ht_table[htidx0][v & m0]; - while (de) { - next = dictGetNext(de); - fn(privdata, de); - de = next; - } - - /* Set unmasked bits so incrementing the reversed cursor - * operates on the masked bits */ - v |= ~m0; - - /* Increment the reverse cursor */ - v = rev(v); - v++; - v = rev(v); - - } else { - htidx0 = 0; - htidx1 = 1; - - /* Make sure t0 is the smaller and t1 is the bigger table */ - if (DICTHT_SIZE(d->ht_size_exp[htidx0]) > DICTHT_SIZE(d->ht_size_exp[htidx1])) { - htidx0 = 1; - htidx1 = 0; - } - - m0 = DICTHT_SIZE_MASK(d->ht_size_exp[htidx0]); - m1 = DICTHT_SIZE_MASK(d->ht_size_exp[htidx1]); - - /* Emit entries at cursor */ - if (defragfns) { - dictDefragBucket(&d->ht_table[htidx0][v & m0], defragfns); - } - de = d->ht_table[htidx0][v & m0]; - while (de) { - next = dictGetNext(de); - fn(privdata, de); - de = next; - } - - /* Iterate over indices in larger table that are the expansion - * of the index pointed to by the cursor in the smaller table */ - do { - /* Emit entries at cursor */ - if (defragfns) { - dictDefragBucket(&d->ht_table[htidx1][v & m1], defragfns); - } - de = d->ht_table[htidx1][v & m1]; - while (de) { - next = dictGetNext(de); - fn(privdata, de); - de = next; - } - - /* Increment the reverse cursor not covered by the smaller mask.*/ - v |= ~m1; - v = rev(v); - v++; - v = rev(v); - - /* Continue while bits covered by mask difference is non-zero */ - } while (v & (m0 ^ m1)); - } - - dictResumeRehashing(d); - - return v; -} - -/* ------------------------- private functions ------------------------------ */ - -/* Because we may need to allocate huge memory chunk at once when dict - * resizes, we will check this allocation is allowed or not if the dict - * type has resizeAllowed member function. */ -static int dictTypeResizeAllowed(dict *d, size_t size) { - if (d->type->resizeAllowed == NULL) return 1; - return d->type->resizeAllowed(DICTHT_SIZE(dictNextExp(size)) * sizeof(dictEntry *), - (double)d->ht_used[0] / DICTHT_SIZE(d->ht_size_exp[0])); -} - -/* Returning DICT_OK indicates a successful expand or the dictionary is undergoing rehashing, - * and there is nothing else we need to do about this dictionary currently. While DICT_ERR indicates - * that expand has not been triggered (may be try shrinking?)*/ -int dictExpandIfNeeded(dict *d) { - /* Incremental rehashing already in progress. Return. */ - if (dictIsRehashing(d)) return DICT_OK; - - /* If the hash table is empty expand it to the initial size. */ - if (DICTHT_SIZE(d->ht_size_exp[0]) == 0) { - dictExpand(d, DICT_HT_INITIAL_SIZE); - return DICT_OK; - } - - /* If we reached the 1:1 ratio, and we are allowed to resize the hash - * table (global setting) or we should avoid it but the ratio between - * elements/buckets is over the "safe" threshold, we resize doubling - * the number of buckets. */ - if ((dict_can_resize == DICT_RESIZE_ENABLE && d->ht_used[0] >= DICTHT_SIZE(d->ht_size_exp[0])) || - (dict_can_resize != DICT_RESIZE_FORBID && - d->ht_used[0] >= dict_force_resize_ratio * DICTHT_SIZE(d->ht_size_exp[0]))) { - if (dictTypeResizeAllowed(d, d->ht_used[0] + 1)) dictExpand(d, d->ht_used[0] + 1); - return DICT_OK; - } - return DICT_ERR; -} - -/* Returning DICT_OK indicates a successful shrinking or the dictionary is undergoing rehashing, - * and there is nothing else we need to do about this dictionary currently. While DICT_ERR indicates - * that shrinking has not been triggered (may be try expanding?)*/ -int dictShrinkIfNeeded(dict *d) { - /* Incremental rehashing already in progress. Return. */ - if (dictIsRehashing(d)) return DICT_OK; - - /* If the size of hash table is DICT_HT_INITIAL_SIZE, don't shrink it. */ - if (DICTHT_SIZE(d->ht_size_exp[0]) <= DICT_HT_INITIAL_SIZE) return DICT_OK; - - /* If we reached below 1:8 elements/buckets ratio, and we are allowed to resize - * the hash table (global setting) or we should avoid it but the ratio is below 1:32, - * we'll trigger a resize of the hash table. */ - if ((dict_can_resize == DICT_RESIZE_ENABLE && - d->ht_used[0] * HASHTABLE_MIN_FILL <= DICTHT_SIZE(d->ht_size_exp[0])) || - (dict_can_resize != DICT_RESIZE_FORBID && - d->ht_used[0] * HASHTABLE_MIN_FILL * dict_force_resize_ratio <= DICTHT_SIZE(d->ht_size_exp[0]))) { - if (dictTypeResizeAllowed(d, d->ht_used[0])) dictShrink(d, d->ht_used[0]); - return DICT_OK; - } - return DICT_ERR; -} - -/* Finds and returns the position within the dict where the provided key should - * be inserted using dictInsertAtPosition if the key does not already exist in - * the dict. If the key exists in the dict, NULL is returned and the optional - * 'existing' entry pointer is populated, if provided. */ -void *dictFindPositionForInsert(dict *d, const void *key, dictEntry **existing) { - unsigned long idx, table; - dictEntry *he; - if (existing) *existing = NULL; - uint64_t hash = dictHashKey(d, key); - idx = hash & DICTHT_SIZE_MASK(d->ht_size_exp[0]); - - if (dictIsRehashing(d)) { - if ((long)idx >= d->rehashidx && d->ht_table[0][idx]) { - /* If we have a valid hash entry at `idx` in ht0, we perform - * rehash on the bucket at `idx` (being more CPU cache friendly) */ - dictBucketRehash(d, idx); - } else { - /* If the hash entry is not in ht0, we rehash the buckets based - * on the rehashidx (not CPU cache friendly). */ - dictRehashStep(d); - } - } - - /* Expand the hash table if needed */ - dictExpandIfAutoResizeAllowed(d); - for (table = 0; table <= 1; table++) { - if (table == 0 && (long)idx < d->rehashidx) continue; - idx = hash & DICTHT_SIZE_MASK(d->ht_size_exp[table]); - /* Search if this slot does not already contain the given key */ - he = d->ht_table[table][idx]; - while (he) { - void *he_key = dictGetKey(he); - if (key == he_key || dictCompareKeys(d, key, he_key)) { - if (existing) *existing = he; - return NULL; - } - he = dictGetNext(he); - } - if (!dictIsRehashing(d)) break; - } - - /* If we are in the process of rehashing the hash table, the bucket is - * always returned in the context of the second (new) hash table. */ - dictEntry **bucket = &d->ht_table[dictIsRehashing(d) ? 1 : 0][idx]; - return bucket; -} - -void dictEmpty(dict *d, void(callback)(dict *)) { - /* Someone may be monitoring a dict that started rehashing, before - * destroying the dict fake completion. */ - if (dictIsRehashing(d) && d->type->rehashingCompleted) d->type->rehashingCompleted(d); - dictClear(d, 0, callback); - dictClear(d, 1, callback); - d->rehashidx = -1; - d->pauserehash = 0; - d->pauseAutoResize = 0; -} - -void dictSetResizeEnabled(dictResizeEnable enable) { - dict_can_resize = enable; -} - -uint64_t dictGetHash(dict *d, const void *key) { - return dictHashKey(d, key); -} - -/* Provides the old and new ht size for a given dictionary during rehashing. This method - * should only be invoked during initialization/rehashing. */ -void dictRehashingInfo(dict *d, unsigned long long *from_size, unsigned long long *to_size) { - /* Invalid method usage if rehashing isn't ongoing. */ - assert(dictIsRehashing(d)); - *from_size = DICTHT_SIZE(d->ht_size_exp[0]); - *to_size = DICTHT_SIZE(d->ht_size_exp[1]); -} - -/* Wrapper functions for gtest to access static internals. */ -unsigned int testOnlyDictGetForceResizeRatio(void) { - return dict_force_resize_ratio; -} - -signed char testOnlyDictNextExp(unsigned long size) { - return dictNextExp(size); -} - -long long testOnlyTimeInMilliseconds(void) { - return timeInMilliseconds(); -} diff --git a/src/dict.h b/src/dict.h index f894e4efcfb..778f93afd74 100644 --- a/src/dict.h +++ b/src/dict.h @@ -1,9 +1,7 @@ -/* Hash Tables Implementation. +/* Dict, a key-value hashtable API. * - * This file implements in-memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto-resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) + * This file implements the dict API as a thin wrapper of the newer hashtable + * API. The dictEntry struct is used as the entry type in underlying hashtable. * * Copyright (c) 2006-2012, Redis Ltd. * All rights reserved. @@ -36,177 +34,263 @@ #ifndef __DICT_H #define __DICT_H -#include "mt19937-64.h" -#include +#include "hashtable.h" +#include "zmalloc.h" #include -#include #define DICT_OK 0 #define DICT_ERR 1 -/* Hash table parameters */ -#define HASHTABLE_MIN_FILL 8 /* Minimal hash table fill 12.5%(100/8) */ - -typedef struct dictEntry dictEntry; /* opaque */ -typedef struct dict dict; - -typedef struct dictType { - /* Callbacks */ - uint64_t (*hashFunction)(const void *key); - void *(*keyDup)(const void *key); - int (*keyCompare)(const void *key1, const void *key2); - void (*keyDestructor)(void *key); - void (*valDestructor)(void *obj); - int (*resizeAllowed)(size_t moreMem, double usedRatio); - /* Invoked at the start of dict initialization/rehashing (old and new ht are already created) */ - void (*rehashingStarted)(dict *d); - /* Invoked at the end of dict initialization/rehashing of all the entries from old to new ht. Both ht still exists - * and are cleaned up after this callback. */ - void (*rehashingCompleted)(dict *d); - /* Allow a dict to carry extra caller-defined metadata. The - * extra memory is initialized to 0 when a dict is allocated. */ - size_t (*dictMetadataBytes)(dict *d); -} dictType; - -#define DICTHT_SIZE(exp) ((exp) == -1 ? 0 : (unsigned long)1 << (exp)) -#define DICTHT_SIZE_MASK(exp) ((exp) == -1 ? 0 : (DICTHT_SIZE(exp)) - 1) - -struct dict { - dictType *type; - - dictEntry **ht_table[2]; - unsigned long ht_used[2]; - - long rehashidx; /* rehashing not in progress if rehashidx == -1 */ - - /* Keep small vars at end for optimal (minimal) struct padding */ - int16_t pauserehash; /* If >0 rehashing is paused (<0 indicates coding error) */ - signed char ht_size_exp[2]; /* exponent of size. (size = 1<0 automatic resizing is disallowed (<0 indicates coding error) */ - void *metadata[]; -}; - -/* If safe is set to 1 this is a safe iterator, that means, you can call - * dictAdd, dictFind, and other functions against the dictionary even while - * iterating. Otherwise it is a non safe iterator, and only dictNext() - * should be called while iterating. */ -typedef struct dictIterator { - dict *d; - long index; - int table, safe; - dictEntry *entry, *nextEntry; - /* unsafe iterator fingerprint for misuse detection. */ - unsigned long long fingerprint; -} dictIterator; - -typedef void(dictScanFunction)(void *privdata, const dictEntry *de); -typedef void *(dictDefragAllocFunction)(void *ptr); -typedef void(dictDefragEntryCb)(void *privdata, void *ptr); -typedef struct { - dictDefragAllocFunction *defragAlloc; /* Used for entries etc. */ - dictDefragAllocFunction *defragKey; /* Defrag-realloc keys (optional) */ - dictDefragAllocFunction *defragVal; /* Defrag-realloc values (optional) */ -} dictDefragFunctions; - -/* This is the initial size of every hash table */ -#define DICT_HT_INITIAL_EXP 2 -#define DICT_HT_INITIAL_SIZE (1 << (DICT_HT_INITIAL_EXP)) - -/* ------------------------------- Macros ------------------------------------*/ -static inline int dictCompareKeys(dict *d, const void *key1, const void *key2) { - if (d->type->keyCompare) { - return d->type->keyCompare(key1, key2); - } else { - return (key1 == key2); +/* dict is now an alias for hashtable */ +typedef hashtable dict; +typedef hashtableType dictType; +typedef hashtableIterator dictIterator; + +/* dictEntry represents a key-value pair for use with hashtable */ +typedef struct dictEntry { + void *key; + union { + void *val; + uint64_t u64; + int64_t s64; + double d; + } v; +} dictEntry; + +#define dictSize(d) hashtableSize(d) +#define dictIsEmpty(d) (hashtableSize(d) == 0) +#define dictIsRehashing(d) hashtableIsRehashing(d) +#define dictCreate(type) hashtableCreate(type) +#define dictRelease(d) hashtableRelease(d) +#define dictEmpty(d, callback) hashtableEmpty(d, callback) +#define dictGetSomeKeys(d, dst, count) hashtableSampleEntries(d, dst, count) +#define dictGenHashFunction(key, len) hashtableGenHashFunction(key, len) +#define dictGenCaseHashFunction(buf, len) hashtableGenCaseHashFunction(buf, len) +#define dictRehashMicroseconds(d, us) hashtableRehashMicroseconds(d, us) +#define dictGetIterator(d) hashtableCreateIterator(d, 0) +#define dictGetSafeIterator(d) hashtableCreateIterator(d, HASHTABLE_ITER_SAFE) +#define dictReleaseIterator(iter) hashtableReleaseIterator(iter) +#define dictInitIterator(iter, d) hashtableInitIterator(iter, d, 0) +#define dictInitSafeIterator(iter, d) hashtableInitIterator(iter, d, HASHTABLE_ITER_SAFE) +#define dictResetIterator(iter) hashtableCleanupIterator(iter) + +/* Expand the hash table if needed. Returns DICT_OK if expand was performed + * or if the dictionary is already large enough, DICT_ERR if expand was not + * performed. */ +static inline int dictExpand(dict *d, unsigned long size) { + return hashtableExpand(d, size) ? DICT_OK : DICT_ERR; +} + +/* Entry accessor functions */ +static inline void dictSetKey(dict *d, dictEntry *de, void *key) { + (void)d; + de->key = key; +} + +static inline void dictSetVal(dict *d, dictEntry *de, void *val) { + (void)d; + de->v.val = val; +} + +static inline void dictSetSignedIntegerVal(dictEntry *de, int64_t val) { + de->v.s64 = val; +} + +static inline void dictSetUnsignedIntegerVal(dictEntry *de, uint64_t val) { + de->v.u64 = val; +} + +static inline void dictSetDoubleVal(dictEntry *de, double val) { + de->v.d = val; +} + +static inline int64_t dictIncrSignedIntegerVal(dictEntry *de, int64_t val) { + de->v.s64 += val; + return de->v.s64; +} + +static inline uint64_t dictIncrUnsignedIntegerVal(dictEntry *de, uint64_t val) { + de->v.u64 += val; + return de->v.u64; +} + +static inline double dictIncrDoubleVal(dictEntry *de, double val) { + de->v.d += val; + return de->v.d; +} + +static inline void *dictGetKey(const dictEntry *de) { + return de->key; +} + +/* Callback for dictType.entryGetKey, which expects void pointers. */ +static inline const void *dictEntryGetKey(const void *entry) { + return dictGetKey((const dictEntry *)entry); +} + +static inline void *dictGetVal(const dictEntry *de) { + return de->v.val; +} + +static inline int64_t dictGetSignedIntegerVal(const dictEntry *de) { + return de->v.s64; +} + +static inline uint64_t dictGetUnsignedIntegerVal(const dictEntry *de) { + return de->v.u64; +} + +static inline double dictGetDoubleVal(const dictEntry *de) { + return de->v.d; +} + +static inline double *dictGetDoubleValPtr(dictEntry *de) { + return &de->v.d; +} + +static inline size_t dictEntryMemUsage(dictEntry *de) { + return sizeof(*de); +} + +static inline size_t dictMemUsage(const dict *d) { + return hashtableMemUsage(d) + hashtableSize(d) * sizeof(dictEntry); +} + +/* Search for a key in the dictionary. Returns the dictEntry if found, + * or NULL if the key doesn't exist. */ +static inline dictEntry *dictFind(dict *d, const void *key) { + void *found = NULL; + return hashtableFind(d, key, &found) ? (dictEntry *)found : NULL; +} + +/* Fetch the value associated with a key. Returns the value if the key exists, + * or NULL if the key doesn't exist. */ +static inline void *dictFetchValue(dict *d, const void *key) { + dictEntry *de = dictFind(d, key); + return de ? de->v.val : NULL; +} + +/* Remove a key from the dictionary. Returns DICT_OK if the key was found + * and removed, DICT_ERR if the key was not found. */ +static inline int dictDelete(dict *d, const void *key) { + return hashtableDelete(d, key) ? DICT_OK : DICT_ERR; +} + +/* Free an entry that was previously unlinked with dictUnlink(). + * It's safe to call this function with de = NULL. */ +static inline void dictFreeUnlinkedEntry(dict *d, dictEntry *de) { + if (de == NULL) return; + hashtableType *type = hashtableGetType(d); + type->entryDestructor(de); +} + +/* Return a random entry from the hash table. */ +static inline dictEntry *dictGetRandomKey(dict *d) { + void *entry = NULL; + return hashtableRandomEntry(d, &entry) ? (dictEntry *)entry : NULL; +} + +/* A more fair random entry selection that considers chain lengths. + * This provides better distribution than dictGetRandomKey(). */ +static inline dictEntry *dictGetFairRandomKey(dict *d) { + void *entry = NULL; + return hashtableFairRandomEntry(d, &entry) ? (dictEntry *)entry : NULL; +} + +/* Remove an element from the table, but without actually releasing + * the key, value and dictionary entry. The dictionary entry is returned + * if the element was found (and unlinked from the table), and the user + * should later call `dictFreeUnlinkedEntry()` with it in order to release + * it. Otherwise if the key is not found, NULL is returned. + * + * This function is useful when we want to remove something from the hash + * table but want to use its value before actually deleting the entry. + * Without this function the pattern would require two lookups. */ +static inline dictEntry *dictUnlink(dict *d, const void *key) { + void *entry = NULL; + return hashtablePop(d, key, &entry) ? (dictEntry *)entry : NULL; +} + +/* Add an entry to the dictionary. */ +static inline int dictAdd(dict *d, void *key, void *val) { + hashtablePosition pos; + void *existing = NULL; + + if (!hashtableFindPositionForInsert(d, key, &pos, &existing)) { + return DICT_ERR; /* Key already exists */ } + + dictEntry *entry = (dictEntry *)zmalloc(sizeof(*entry)); + entry->key = key; + entry->v.val = val; + hashtableInsertAtPosition(d, entry, &pos); + return DICT_OK; } -#define dictMetadata(d) (&(d)->metadata) -#define dictMetadataSize(d) ((d)->type->dictMetadataBytes ? (d)->type->dictMetadataBytes(d) : 0) - -#define dictHashKey(d, key) ((d)->type->hashFunction(key)) -#define dictBuckets(d) (DICTHT_SIZE((d)->ht_size_exp[0]) + DICTHT_SIZE((d)->ht_size_exp[1])) -#define dictSize(d) ((d)->ht_used[0] + (d)->ht_used[1]) -#define dictIsEmpty(d) ((d)->ht_used[0] == 0 && (d)->ht_used[1] == 0) -#define dictIsRehashing(d) ((d)->rehashidx != -1) -#define dictPauseRehashing(d) ((d)->pauserehash++) -#define dictResumeRehashing(d) ((d)->pauserehash--) -#define dictIsRehashingPaused(d) ((d)->pauserehash > 0) -#define dictPauseAutoResize(d) ((d)->pauseAutoResize++) -#define dictResumeAutoResize(d) ((d)->pauseAutoResize--) - -/* If our unsigned long type can store a 64 bit number, use a 64 bit PRNG. */ -#if ULONG_MAX >= 0xffffffffffffffff -#define randomULong() ((unsigned long)genrand64_int64()) -#else -#define randomULong() random() -#endif - -typedef enum { - DICT_RESIZE_ENABLE, - DICT_RESIZE_AVOID, - DICT_RESIZE_FORBID, -} dictResizeEnable; - -/* API */ -dict *dictCreate(dictType *type); -int dictExpand(dict *d, unsigned long size); -int dictTryExpand(dict *d, unsigned long size); -int dictShrink(dict *d, unsigned long size); -int dictAdd(dict *d, void *key, void *val); -dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing); -void *dictFindPositionForInsert(dict *d, const void *key, dictEntry **existing); -dictEntry *dictInsertAtPosition(dict *d, void *key, void *position); -dictEntry *dictAddOrFind(dict *d, void *key); -int dictReplace(dict *d, void *key, void *val); -int dictDelete(dict *d, const void *key); -dictEntry *dictUnlink(dict *d, const void *key); -void dictFreeUnlinkedEntry(dict *d, dictEntry *he); -void dictRelease(dict *d); -dictEntry *dictFind(dict *d, const void *key); -void *dictFetchValue(dict *d, const void *key); -int dictShrinkIfNeeded(dict *d); -int dictExpandIfNeeded(dict *d); -void dictSetKey(dict *d, dictEntry *de, void *key); -void dictSetVal(dict *d, dictEntry *de, void *val); -void dictSetSignedIntegerVal(dictEntry *de, int64_t val); -void dictSetUnsignedIntegerVal(dictEntry *de, uint64_t val); -void dictSetDoubleVal(dictEntry *de, double val); -int64_t dictIncrSignedIntegerVal(dictEntry *de, int64_t val); -uint64_t dictIncrUnsignedIntegerVal(dictEntry *de, uint64_t val); -double dictIncrDoubleVal(dictEntry *de, double val); -void *dictGetKey(const dictEntry *de); -void *dictGetVal(const dictEntry *de); -int64_t dictGetSignedIntegerVal(const dictEntry *de); -uint64_t dictGetUnsignedIntegerVal(const dictEntry *de); -double dictGetDoubleVal(const dictEntry *de); -double *dictGetDoubleValPtr(dictEntry *de); -size_t dictMemUsage(const dict *d); -size_t dictEntryMemUsage(dictEntry *de); -dictIterator *dictGetIterator(dict *d); -dictIterator *dictGetSafeIterator(dict *d); -void dictInitIterator(dictIterator *iter, dict *d); -void dictInitSafeIterator(dictIterator *iter, dict *d); -void dictResetIterator(dictIterator *iter); -dictEntry *dictNext(dictIterator *iter); -dictEntry *dictGetNext(const dictEntry *de); -void dictReleaseIterator(dictIterator *iter); -dictEntry *dictGetRandomKey(dict *d); -dictEntry *dictGetFairRandomKey(dict *d); -unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count); -void dictGetStats(char *buf, size_t bufsize, dict *d, int full); -uint64_t dictGenHashFunction(const void *key, size_t len); -uint64_t dictGenCaseHashFunction(const unsigned char *buf, size_t len); -void dictEmpty(dict *d, void(callback)(dict *)); -void dictSetResizeEnabled(dictResizeEnable enable); -int dictRehash(dict *d, int n); -int dictRehashMicroseconds(dict *d, uint64_t us); -void dictSetHashFunctionSeed(uint8_t *seed); -uint8_t *dictGetHashFunctionSeed(void); -unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, void *privdata); -unsigned long -dictScanDefrag(dict *d, unsigned long v, dictScanFunction *fn, const dictDefragFunctions *defragfns, void *privdata); -uint64_t dictGetHash(dict *d, const void *key); -void dictRehashingInfo(dict *d, unsigned long long *from_size, unsigned long long *to_size); +/* Adds a key to the dictionary without setting a value. + * + * If key already exists, NULL is returned, and "*existing" is populated + * with the existing entry if existing is not NULL. + * + * If key was added, the dictEntry is returned to be manipulated by the + * caller. */ +static inline dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing) { + hashtablePosition pos; + void *existing_entry = NULL; + + if (!hashtableFindPositionForInsert(d, key, &pos, &existing_entry)) { + if (existing) *existing = (dictEntry *)existing_entry; + return NULL; + } + + dictEntry *entry = (dictEntry *)zmalloc(sizeof(*entry)); + entry->key = key; + hashtableInsertAtPosition(d, entry, &pos); + if (existing) *existing = NULL; + return entry; +} + +/* Adds a key to the dictionary if it doesn't already exists. Returns the + * dictEntry of the key, whether it was just added or not. */ +static inline dictEntry *dictAddOrFind(dict *d, void *key) { + dictEntry *existing = NULL; + dictEntry *entry = dictAddRaw(d, key, &existing); + return entry ? entry : existing; +} + +/* Adds an element to the dictionary. If the key already exists, the old + * value is replaced with the new one. + * + * Always returns 1 to indicate the key was consumed (either added or used + * to replace). The caller should not free the key after calling this. */ +static inline int dictReplace(dict *d, void *key, void *val) { + dictEntry *entry = (dictEntry *)zmalloc(sizeof(*entry)); + entry->key = key; + entry->v.val = val; + + void *existing = NULL; + if (hashtableAddOrFind(d, entry, &existing)) { + return 1; /* Entry was added */ + } + + /* Entry already exists. Put the old value in our new entry and free it. */ + dictEntry *existing_entry = (dictEntry *)existing; + entry->v.val = existing_entry->v.val; + hashtableType *type = hashtableGetType(d); + type->entryDestructor(entry); + + /* Update the existing entry with the new value. */ + existing_entry->v.val = val; + return 1; +} + +/* Iterator operations */ +static inline dictEntry *dictNext(dictIterator *iter) { + void *entry = NULL; + if (hashtableNext(iter, &entry)) { + return (dictEntry *)entry; + } + return NULL; +} #endif /* __DICT_H */ diff --git a/src/eval.c b/src/eval.c index 0baba539535..5f56f782fa1 100644 --- a/src/eval.c +++ b/src/eval.c @@ -71,18 +71,20 @@ static void dictScriptDestructor(void *val) { zfree(es); } -static uint64_t dictStrCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char *)key, strlen((char *)key)); +/* Helper functions for eval.c */ +static void dictEntryDestructorSdsKeyScriptValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + dictScriptDestructor(dictGetVal(de)); + zfree(de); } /* evalCtx.scripts sha (as sds string) -> scripts (as evalScript) cache. */ dictType shaScriptObjectDictType = { - dictStrCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictScriptDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyScriptValue, }; /* Eval context */ diff --git a/src/expire.c b/src/expire.c index adf32ea4a04..b31f57465cc 100644 --- a/src/expire.c +++ b/src/expire.c @@ -605,15 +605,14 @@ void expireReplicaKeys(void) { /* Track keys that received an EXPIRE or similar command in the context * of a writable replica. */ + void rememberReplicaKeyWithExpire(serverDb *db, robj *key) { if (replicaKeysWithExpire == NULL) { static dictType dt = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; replicaKeysWithExpire = dictCreate(&dt); } diff --git a/src/expire.h b/src/expire.h index 3923f383119..cb6103f01e6 100644 --- a/src/expire.h +++ b/src/expire.h @@ -55,7 +55,6 @@ enum activeExpiryType { typedef struct client client; typedef struct serverObject robj; typedef struct serverDb serverDb; -typedef struct dict dict; /* return the relevant expiration policy based on the current server state and the provided flags. * FLAGS can indicate either: diff --git a/src/functions.c b/src/functions.c index 584d3421c6c..f8b8bc39a23 100644 --- a/src/functions.c +++ b/src/functions.c @@ -69,44 +69,53 @@ typedef struct functionsLibMetaData { sds code; } functionsLibMetaData; -static uint64_t dictStrCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char *)key, strlen((char *)key)); -} - dictType functionDictType = { - dictStrCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; +static void dictEntryDestructorSdsKeyEngineStatsValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + engineStatsDispose(dictGetVal(de)); + zfree(de); +} + dictType engineStatsDictType = { - dictSdsCaseHash, /* hash function */ - dictSdsDup, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - engineStatsDispose, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyEngineStatsValue, }; +static void dictEntryDestructorSdsKeyEngineFunctionValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + engineFunctionDispose(dictGetVal(de)); + zfree(de); +} + dictType libraryFunctionDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - engineFunctionDispose, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyEngineFunctionValue, }; +static void dictEntryDestructorSdsKeyEngineLibraryValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + engineLibraryDispose(dictGetVal(de)); + zfree(de); +} + dictType librariesDictType = { - dictSdsHash, /* hash function */ - dictSdsDup, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - engineLibraryDispose, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyEngineLibraryValue, }; /* Libraries Ctx. */ @@ -239,7 +248,7 @@ static void initializeFunctionsLibEngineStats(scriptingEngine *engine, void *context) { functionsLibCtx *lib_ctx = (functionsLibCtx *)context; functionsLibEngineStats *stats = zcalloc(sizeof(*stats)); - dictAdd(lib_ctx->engines_stats, scriptingEngineGetName(engine), stats); + dictAdd(lib_ctx->engines_stats, sdsdup(scriptingEngineGetName(engine)), stats); } /* Create a new functions ctx */ @@ -258,7 +267,7 @@ void functionsAddEngineStats(sds engine_name) { dictEntry *entry = dictFind(curr_functions_lib_ctx->engines_stats, engine_name); if (entry == NULL) { functionsLibEngineStats *stats = zcalloc(sizeof(*stats)); - dictAdd(curr_functions_lib_ctx->engines_stats, engine_name, stats); + dictAdd(curr_functions_lib_ctx->engines_stats, sdsdup(engine_name), stats); } } @@ -349,7 +358,7 @@ static void libraryLink(functionsLibCtx *lib_ctx, functionLibInfo *li) { } dictReleaseIterator(iter); - dictAdd(lib_ctx->libraries, li->name, li); + dictAdd(lib_ctx->libraries, sdsdup(li->name), li); lib_ctx->cache_memory += libraryMallocSize(li); /* update stats */ diff --git a/src/fuzzer_command_generator.c b/src/fuzzer_command_generator.c index 2a6479e013e..c9d486101c2 100644 --- a/src/fuzzer_command_generator.c +++ b/src/fuzzer_command_generator.c @@ -296,21 +296,22 @@ static int sdsKeyCompare(const void *key1, const void *key2) { } static uint64_t sdsHash(const void *key) { - return dictGenHashFunction((unsigned char *)key, sdslen((char *)key)); + return dictGenHashFunction(key, sdslen(key)); } -static void sdsDestructor(void *val) { - sdsfree(val); +static void dictEntryDestructorSdsKeyConfigVal(void *entry) { + dictEntry *de = entry; + sdsfree(dictGetKey(de)); + configDictValDestructor(dictGetVal(de)); + zfree(de); } /* Dictionary type for config entries */ static dictType configDictType = { - sdsHash, /* hash function */ - NULL, /* key dup */ - sdsKeyCompare, /* key compare */ - sdsDestructor, /* key destructor */ - configDictValDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = sdsHash, + .keyCompare = sdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyConfigVal, }; dict *initConfigDict(void) { diff --git a/src/hashtable.c b/src/hashtable.c index bd5c902d102..dcae6dfa014 100644 --- a/src/hashtable.c +++ b/src/hashtable.c @@ -406,7 +406,7 @@ static inline int compareKeys(hashtable *ht, const void *key1, const void *key2) if (ht->type->keyCompare != NULL) { return ht->type->keyCompare(key1, key2); } else { - return key1 != key2; + return key1 == key2; } } @@ -801,7 +801,7 @@ static inline int checkCandidateInBucket(hashtable *ht, bucket *b, int pos, cons /* It's a candidate. */ void *entry = b->entries[pos]; const void *elem_key = entryGetKey(ht, entry); - if (compareKeys(ht, key, elem_key) == 0) { + if (compareKeys(ht, key, elem_key)) { /* It's a match. */ assert(pos_in_bucket != NULL); if (!validateElementIfNeeded(ht, entry)) { @@ -1348,7 +1348,7 @@ unsigned hashtableEntriesPerBucket(void) { /* Returns the size of the hashtable structures, in bytes (not including the sizes * of the entries, if the entries are pointers to allocated objects). */ -size_t hashtableMemUsage(hashtable *ht) { +size_t hashtableMemUsage(const hashtable *ht) { size_t num_buckets = numBuckets(ht->bucket_exp[0]) + numBuckets(ht->bucket_exp[1]); num_buckets += ht->child_buckets[0] + ht->child_buckets[1]; size_t metasize = ht->type->getMetadataSize ? ht->type->getMetadataSize() : 0; @@ -1879,7 +1879,7 @@ bool hashtableIncrementalFindStep(hashtableIncrementalFindState *state) { hashtable *ht = data->hashtable; void *entry = data->bucket->entries[data->pos]; const void *elem_key = entryGetKey(ht, entry); - if (compareKeys(ht, data->key, elem_key) == 0) { + if (compareKeys(ht, data->key, elem_key)) { /* It's a match. */ data->state = HASHTABLE_FOUND; return false; diff --git a/src/hashtable.h b/src/hashtable.h index cac8f2c5eb6..8bbf5d8c05b 100644 --- a/src/hashtable.h +++ b/src/hashtable.h @@ -125,7 +125,7 @@ size_t hashtableSize(const hashtable *ht); size_t hashtableBuckets(hashtable *ht); size_t hashtableChainedBuckets(hashtable *ht, int table); unsigned hashtableEntriesPerBucket(void); -size_t hashtableMemUsage(hashtable *ht); +size_t hashtableMemUsage(const hashtable *ht); void hashtablePauseAutoShrink(hashtable *ht); void hashtableResumeAutoShrink(hashtable *ht); bool hashtableIsRehashing(hashtable *ht); diff --git a/src/latency.c b/src/latency.c index d69f86981fd..f71094c3949 100644 --- a/src/latency.c +++ b/src/latency.c @@ -37,21 +37,19 @@ #include "hdr_histogram.h" /* Dictionary type for latency events. */ -int dictStringKeyCompare(const void *key1, const void *key2) { - return strcmp(key1, key2) == 0; -} -uint64_t dictStringHash(const void *key) { - return dictGenHashFunction(key, strlen(key)); +static void dictEntryDestructorHeapKeyValue(void *entry) { + dictEntry *de = entry; + zfree(dictGetKey(de)); + zfree(dictGetVal(de)); + zfree(de); } dictType latencyTimeSeriesDictType = { - dictStringHash, /* hash function */ - NULL, /* key dup */ - dictStringKeyCompare, /* key compare */ - dictVanillaFree, /* key destructor */ - dictVanillaFree, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrHash, + .keyCompare = dictCStrKeyCompare, + .entryDestructor = dictEntryDestructorHeapKeyValue, }; /* ------------------------- Utility functions ------------------------------ */ diff --git a/src/module.c b/src/module.c index de5a5510e40..94780983143 100644 --- a/src/module.c +++ b/src/module.c @@ -12466,21 +12466,11 @@ size_t moduleGetMemUsage(robj *key, robj *val, size_t sample_size, int dbid) { /* 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)); -} - -int dictCStringKeyCompare(const void *key1, const void *key2) { - return strcmp(key1, key2) == 0; -} - dictType moduleAPIDictType = { - dictCStringKeyHash, /* hash function */ - NULL, /* key dup */ - dictCStringKeyCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrHash, + .keyCompare = dictCStrKeyCompare, + .entryDestructor = zfree, }; int moduleRegisterApi(const char *funcname, void *funcptr) { @@ -12503,14 +12493,18 @@ void moduleRegisterCoreAPI(void); void moduleInitModulesSystemLast(void) { } +static void dictEntryDestructorSdsKeyValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + dictSdsDestructor(dictGetVal(de)); + zfree(de); +} dictType sdsKeyValueHashDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictSdsDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyValue, }; void moduleInitModulesSystem(void) { diff --git a/src/rdb.c b/src/rdb.c index 0bd4cf1eb6b..7b7ad719eef 100644 --- a/src/rdb.c +++ b/src/rdb.c @@ -144,13 +144,18 @@ typedef struct { rdbAuxFieldDecoder decoder; } rdbAuxFieldCodec; +static void dictEntryDestructorSdsKeyHeapValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + dictVanillaFree(dictGetVal(de)); + zfree(de); +} + dictType rdbAuxFieldDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictVanillaFree, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyHeapValue, }; dict *rdbAuxFields = NULL; diff --git a/src/scripting_engine.c b/src/scripting_engine.c index c923e1e956f..750b9564b08 100644 --- a/src/scripting_engine.c +++ b/src/scripting_engine.c @@ -65,17 +65,11 @@ static engineManager engineMgr = { .total_memory_overhead = 0, }; -static uint64_t dictStrCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char *)key, strlen((char *)key)); -} - dictType engineDictType = { - dictStrCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = zfree, }; static int isCalledFromAsyncThread(void) { diff --git a/src/sentinel.c b/src/sentinel.c index f7b051dad22..5c98f2328cb 100644 --- a/src/sentinel.c +++ b/src/sentinel.c @@ -439,13 +439,25 @@ void dictInstancesValDestructor(void *obj) { * * also used for: sentinelValkeyInstance->sentinels dictionary that maps * sentinels ip:port to last seen time in Pub/Sub hello message. */ + +static void dictEntryDestructorInstancesValue(void *entry) { + dictEntry *de = entry; + dictInstancesValDestructor(dictGetVal(de)); + zfree(de); +} + +static void dictEntryDestructorSdsKeyValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + dictSdsDestructor(dictGetVal(de)); + zfree(de); +} + dictType instancesDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - NULL, /* key destructor */ - dictInstancesValDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorInstancesValue, }; /* Instance runid (sds) -> votes (long casted to void*) @@ -453,22 +465,18 @@ dictType instancesDictType = { * This is useful into sentinelGetObjectiveLeader() function in order to * count the votes and understand who is the leader. */ dictType leaderVotesDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = zfree, }; /* Instance renamed commands table. */ dictType renamedCommandsDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictSdsDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyValue, }; /* =========================== Initialization =============================== */ @@ -4024,7 +4032,7 @@ void sentinelCommand(client *c) { * a dictionary composed of just the primary groups the user * requested. */ dictType copy_keeper = instancesDictType; - copy_keeper.valDestructor = NULL; + copy_keeper.entryDestructor = zfree; dict *primaries_local = sentinel.primaries; if (c->argc > 2) { primaries_local = dictCreate(©_keeper); @@ -4164,7 +4172,7 @@ void sentinelInfoCommand(client *c) { if (sdslen(info) != 0) info = sdscat(info, "\r\n"); info = sdscatprintf(info, "# Sentinel\r\n" - "sentinel_masters:%lu\r\n" + "sentinel_masters:%zu\r\n" "sentinel_tilt:%d\r\n" "sentinel_tilt_since_seconds:%jd\r\n" "sentinel_total_tilt:%d\r\n" @@ -4187,7 +4195,7 @@ void sentinelInfoCommand(client *c) { status = "sdown"; info = sdscatprintf(info, "master%d:name=%s,status=%s,address=%s:%d," - "slaves=%lu,sentinels=%lu\r\n", + "slaves=%zu,sentinels=%zu\r\n", primary_id++, ri->name, status, announceSentinelAddr(ri->addr), ri->addr->port, dictSize(ri->replicas), dictSize(ri->sentinels) + 1); } diff --git a/src/server.c b/src/server.c index 69d0cd27ab0..318714d68d4 100644 --- a/src/server.c +++ b/src/server.c @@ -385,23 +385,12 @@ int dictSdsKeyCompare(const void *key1, const void *key2) { return memcmp(key1, key2, l1) == 0; } -/* Returns 0 when keys match */ -int hashtableSdsKeyCompare(const void *key1, const void *key2) { - const sds sds1 = (const sds)key1, sds2 = (const sds)key2; - return sdslen(sds1) != sdslen(sds2) || sdscmp(sds1, sds2); -} - /* A case insensitive version used for the command lookup table and other * places where case insensitive non binary-safe comparison is needed. */ int dictSdsKeyCaseCompare(const void *key1, const void *key2) { return strcasecmp(key1, key2) == 0; } -/* Case insensitive key comparison */ -int hashtableStringKeyCaseCompare(const void *key1, const void *key2) { - return strcasecmp(key1, key2); -} - void dictObjectDestructor(void *val) { if (val == NULL) return; /* Lazy freeing will set value to NULL. */ decrRefCount(val); @@ -411,10 +400,6 @@ void dictSdsDestructor(void *val) { sdsfree(val); } -void *dictSdsDup(const void *key) { - return sdsdup((const sds)key); -} - int dictObjKeyCompare(const void *key1, const void *key2) { const robj *o1 = key1, *o2 = key2; return dictSdsKeyCompare(objectGetVal(o1), objectGetVal(o2)); @@ -426,21 +411,40 @@ uint64_t dictObjHash(const void *key) { } uint64_t dictSdsHash(const void *key) { - return dictGenHashFunction((unsigned char *)key, sdslen((char *)key)); + return dictGenHashFunction(key, sdslen(key)); +} + +/* Hash function using a configurable seed (set via hash-seed config). + * Used for data hashtables (keys, sets, zsets, hashes) where deterministic + * iteration order across cluster nodes is needed. */ +static uint8_t configurable_hash_seed[16]; + +extern uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k); + +void setConfigurableHashSeed(uint8_t *seed) { + memcpy(configurable_hash_seed, seed, sizeof(configurable_hash_seed)); +} + +uint64_t genHashFunctionConfigurableSeed(const char *buf, size_t len) { + return siphash((const uint8_t *)buf, len, configurable_hash_seed); +} + +uint64_t sdsHashConfigurableSeed(const void *key) { + return genHashFunctionConfigurableSeed(key, sdslen(key)); } uint64_t dictSdsCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char *)key, sdslen((char *)key)); + return dictGenCaseHashFunction(key, sdslen(key)); } /* Dict hash function for null terminated string */ uint64_t dictCStrHash(const void *key) { - return dictGenHashFunction((unsigned char *)key, strlen((char *)key)); + return dictGenHashFunction(key, strlen(key)); } /* Dict hash function for null terminated string */ uint64_t dictCStrCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char *)key, strlen((char *)key)); + return dictGenCaseHashFunction(key, strlen((char *)key)); } /* Hash function for client */ @@ -448,18 +452,14 @@ uint64_t hashtableClientHash(const void *key) { return ((client *)key)->id; } -/* Hashtable compare function for client, 0 means equal. */ +/* Hashtable compare function for client */ int hashtableClientKeyCompare(const void *key1, const void *key2) { - return ((client *)key1)->id != ((client *)key2)->id; + return ((client *)key1)->id == ((client *)key2)->id; } /* Dict compare function for null terminated string */ int dictCStrKeyCompare(const void *key1, const void *key2) { - int l1, l2; - l1 = strlen((char *)key1); - l2 = strlen((char *)key2); - if (l1 != l2) return 0; - return memcmp(key1, key2, l1) == 0; + return strcmp(key1, key2) == 0; } /* Dict case insensitive compare function for null terminated string */ @@ -485,11 +485,6 @@ int dictEncObjKeyCompare(const void *key1, const void *key2) { return cmp; } -/* Returns 0 when keys match */ -int hashtableEncObjKeyCompare(const void *key1, const void *key2) { - return !dictEncObjKeyCompare(key1, key2); -} - uint64_t dictEncObjHash(const void *key) { robj *o = (robj *)key; @@ -500,7 +495,7 @@ uint64_t dictEncObjHash(const void *key) { int len; len = ll2string(buf, 32, (long)objectGetVal(o)); - return dictGenHashFunction((unsigned char *)buf, len); + return dictGenHashFunction(buf, len); } else { serverPanic("Unknown string encoding"); } @@ -534,39 +529,90 @@ const void *hashtableSubcommandGetKey(const void *element) { return command->declared_name; } +/* Helper function to get key from dictEntry - used as entryGetKey callback */ +/* Entry destructor that frees object key and the dictEntry itself */ +void dictEntryDestructorObjectKey(void *entry) { + dictEntry *de = entry; + dictObjectDestructor(dictGetKey(de)); + zfree(de); +} + +/* Entry destructor that frees object key, heap pointer value, and the dictEntry itself */ +void dictEntryDestructorObjectKeyHeapValue(void *entry) { + dictEntry *de = entry; + dictObjectDestructor(dictGetKey(de)); + zfree(dictGetVal(de)); + zfree(de); +} + +/* Entry destructor that frees object key, list value, and the dictEntry itself */ +void dictEntryDestructorObjectKeyListValue(void *entry) { + dictEntry *de = entry; + dictObjectDestructor(dictGetKey(de)); + dictListDestructor(dictGetVal(de)); + zfree(de); +} + +/* Entry destructor that frees object key, hashtable value, and the dictEntry itself */ +void dictEntryDestructorObjectKeyHashtableValue(void *entry) { + dictEntry *de = entry; + dictObjectDestructor(dictGetKey(de)); + dictHashtableDestructor(dictGetVal(de)); + zfree(de); +} + +/* Entry destructor that frees SDS key and the dictEntry itself */ +void dictEntryDestructorSdsKey(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + zfree(de); +} + +/* Entry destructor that frees SDS key, list value, and the dictEntry itself */ +void dictEntryDestructorSdsKeyListValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + dictListDestructor(dictGetVal(de)); + zfree(de); +} + +/* Entry destructor that frees SDS key, heap pointer value, and the dictEntry itself */ +void dictEntryDestructorSdsKeyHeapValue(void *entry) { + dictEntry *de = entry; + dictSdsDestructor(dictGetKey(de)); + zfree(dictGetVal(de)); + zfree(de); +} + /* Generic hash table type where keys are Objects, Values * dummy pointers. */ dictType objectKeyPointerValueDictType = { - dictEncObjHash, /* hash function */ - NULL, /* key dup */ - dictEncObjKeyCompare, /* key compare */ - dictObjectDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictEncObjHash, + .keyCompare = dictEncObjKeyCompare, + .entryDestructor = dictEntryDestructorObjectKey, }; /* Like objectKeyPointerValueDictType(), but values can be destroyed, if * not NULL, calling zfree(). */ dictType objectKeyHeapPointerValueDictType = { - dictEncObjHash, /* hash function */ - NULL, /* key dup */ - dictEncObjKeyCompare, /* key compare */ - dictObjectDestructor, /* key destructor */ - dictVanillaFree, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictEncObjHash, + .keyCompare = dictEncObjKeyCompare, + .entryDestructor = dictEntryDestructorObjectKeyHeapValue, }; /* Generic hashtable type: set of robj elements */ hashtableType objectHashtableType = { .hashFunction = dictEncObjHash, - .keyCompare = hashtableEncObjKeyCompare, + .keyCompare = dictEncObjKeyCompare, .entryDestructor = dictObjectDestructor, }; /* Set hashtable type. Items are SDS strings */ hashtableType setHashtableType = { - .hashFunction = dictSdsHash, - .keyCompare = hashtableSdsKeyCompare, + .hashFunction = sdsHashConfigurableSeed, + .keyCompare = dictSdsKeyCompare, .entryDestructor = dictSdsDestructor}; const void *zsetHashtableGetKey(const void *element) { @@ -576,9 +622,9 @@ const void *zsetHashtableGetKey(const void *element) { /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ hashtableType zsetHashtableType = { - .hashFunction = dictSdsHash, + .hashFunction = sdsHashConfigurableSeed, .entryGetKey = zsetHashtableGetKey, - .keyCompare = hashtableSdsKeyCompare, + .keyCompare = dictSdsKeyCompare, }; uint64_t hashtableSdsHash(const void *key) { @@ -598,11 +644,6 @@ void hashtableObjectPrefetchValue(const void *entry) { } } -int hashtableObjKeyCompare(const void *key1, const void *key2) { - const robj *o1 = key1, *o2 = key2; - return hashtableSdsKeyCompare(objectGetVal(o1), objectGetVal(o2)); -} - void hashtableObjectDestructor(void *val) { if (val == NULL) return; /* Lazy freeing will set value to NULL. */ decrRefCount(val); @@ -612,8 +653,8 @@ void hashtableObjectDestructor(void *val) { hashtableType kvstoreKeysHashtableType = { .entryPrefetchValue = hashtableObjectPrefetchValue, .entryGetKey = hashtableObjectGetKey, - .hashFunction = hashtableSdsHash, - .keyCompare = hashtableSdsKeyCompare, + .hashFunction = sdsHashConfigurableSeed, + .keyCompare = dictSdsKeyCompare, .entryDestructor = hashtableObjectDestructor, .resizeAllowed = hashtableResizeAllowed, .rehashingStarted = kvstoreHashtableRehashingStarted, @@ -626,8 +667,8 @@ hashtableType kvstoreKeysHashtableType = { hashtableType kvstoreExpiresHashtableType = { .entryPrefetchValue = hashtableObjectPrefetchValue, .entryGetKey = hashtableObjectGetKey, - .hashFunction = hashtableSdsHash, - .keyCompare = hashtableSdsKeyCompare, + .hashFunction = sdsHashConfigurableSeed, + .keyCompare = dictSdsKeyCompare, .entryDestructor = NULL, /* shared with keyspace table */ .resizeAllowed = hashtableResizeAllowed, .rehashingStarted = kvstoreHashtableRehashingStarted, @@ -639,19 +680,19 @@ hashtableType kvstoreExpiresHashtableType = { /* Command set, hashed by current command name, stores serverCommand structs. */ hashtableType commandSetType = {.entryGetKey = hashtableCommandGetCurrentName, .hashFunction = dictSdsCaseHash, - .keyCompare = hashtableStringKeyCaseCompare, + .keyCompare = dictCStrKeyCaseCompare, .instant_rehashing = 1}; /* Command set, hashed by original command name, stores serverCommand structs. */ hashtableType originalCommandSetType = {.entryGetKey = hashtableCommandGetOriginalName, .hashFunction = dictSdsCaseHash, - .keyCompare = hashtableStringKeyCaseCompare, + .keyCompare = dictCStrKeyCaseCompare, .instant_rehashing = 1}; /* Sub-command set, hashed by char* string, stores serverCommand structs. */ hashtableType subcommandSetType = {.entryGetKey = hashtableSubcommandGetKey, .hashFunction = dictCStrCaseHash, - .keyCompare = hashtableStringKeyCaseCompare, + .keyCompare = dictCStrKeyCaseCompare, .instant_rehashing = 1}; /* Hash type hash table (note that small hashes are represented with listpacks) */ @@ -670,17 +711,17 @@ size_t hashHashtableTypeMetadataSize(void) { extern bool hashHashtableTypeValidate(hashtable *ht, void *entry); hashtableType hashHashtableType = { - .hashFunction = dictSdsHash, + .hashFunction = sdsHashConfigurableSeed, .entryGetKey = hashHashtableTypeGetKey, - .keyCompare = hashtableSdsKeyCompare, + .keyCompare = dictSdsKeyCompare, .entryDestructor = hashHashtableTypeDestructor, .getMetadataSize = hashHashtableTypeMetadataSize, }; hashtableType hashWithVolatileItemsHashtableType = { - .hashFunction = dictSdsHash, + .hashFunction = sdsHashConfigurableSeed, .entryGetKey = hashHashtableTypeGetKey, - .keyCompare = hashtableSdsKeyCompare, + .keyCompare = dictSdsKeyCompare, .entryDestructor = hashHashtableTypeDestructor, .getMetadataSize = hashHashtableTypeMetadataSize, .validateEntry = hashHashtableTypeValidate, @@ -689,29 +730,25 @@ hashtableType hashWithVolatileItemsHashtableType = { /* Hashtable type without destructor */ hashtableType sdsReplyHashtableType = { .hashFunction = dictSdsCaseHash, - .keyCompare = hashtableSdsKeyCompare}; + .keyCompare = dictSdsKeyCompare}; /* Keylist hash table type has unencoded Objects as keys and * lists as values. It's used for blocking operations (BLPOP) and to * map swapped keys to a list of clients waiting for this keys to be loaded. */ dictType keylistDictType = { - dictObjHash, /* hash function */ - NULL, /* key dup */ - dictObjKeyCompare, /* key compare */ - dictObjectDestructor, /* key destructor */ - dictListDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictObjHash, + .keyCompare = dictObjKeyCompare, + .entryDestructor = dictEntryDestructorObjectKeyListValue, }; /* objToHashtableDictType has unencoded Objects as keys and * hashtables as values. It's used for PUBSUB command to track clients subscribing the patterns. */ dictType objToHashtableDictType = { - dictObjHash, /* hash function */ - NULL, /* key dup */ - dictObjKeyCompare, /* key compare */ - dictObjectDestructor, /* key destructor */ - dictHashtableDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictObjHash, + .keyCompare = dictObjKeyCompare, + .entryDestructor = dictEntryDestructorObjectKeyHashtableValue, }; /* Callback used for hash tables where the entries are dicts and the key @@ -735,7 +772,7 @@ void hashtableChannelsDestructor(void *entry) { hashtableType kvstoreChannelHashtableType = { .entryGetKey = hashtableChannelsGetKey, .hashFunction = dictObjHash, - .keyCompare = hashtableObjKeyCompare, + .keyCompare = dictObjKeyCompare, .entryDestructor = hashtableChannelsDestructor, .rehashingStarted = kvstoreHashtableRehashingStarted, .rehashingCompleted = kvstoreHashtableRehashingCompleted, @@ -746,55 +783,45 @@ hashtableType kvstoreChannelHashtableType = { /* Modules system dictionary type. Keys are module name, * values are pointer to ValkeyModule struct. */ dictType modulesDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* Migrate cache dict type. */ dictType migrateCacheDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* Dict for for case-insensitive search using null terminated C strings. * The keys stored in dict are sds though. */ dictType stringSetDictType = { - dictCStrCaseHash, /* hash function */ - NULL, /* key dup */ - dictCStrKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrCaseHash, + .keyCompare = dictCStrKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKey, }; /* Dict for for case-insensitive search using null terminated C strings. * The key and value do not have a destructor. */ dictType externalStringType = { - dictCStrCaseHash, /* hash function */ - NULL, /* key dup */ - dictCStrKeyCaseCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictCStrCaseHash, + .keyCompare = dictCStrKeyCaseCompare, + .entryDestructor = zfree, }; /* Dict for case-insensitive search using sds objects with a zmalloc * allocated object as the value. */ dictType sdsHashDictType = { - dictSdsCaseHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCaseCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictVanillaFree, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsCaseHash, + .keyCompare = dictSdsKeyCaseCompare, + .entryDestructor = dictEntryDestructorSdsKeyHeapValue, }; size_t clientHashtableTypeMetadataSize(void) { @@ -816,13 +843,10 @@ hashtableType clientHashtableType = { * active fork child running. */ void updateDictResizePolicy(void) { if (server.in_fork_child != CHILD_TYPE_NONE || !server.dict_resizing) { - dictSetResizeEnabled(DICT_RESIZE_FORBID); hashtableSetResizePolicy(HASHTABLE_RESIZE_FORBID); } else if (hasActiveChildProcess()) { - dictSetResizeEnabled(DICT_RESIZE_AVOID); hashtableSetResizePolicy(HASHTABLE_RESIZE_AVOID); } else { - dictSetResizeEnabled(DICT_RESIZE_ENABLE); hashtableSetResizePolicy(HASHTABLE_RESIZE_ALLOW); } } @@ -6207,7 +6231,7 @@ sds genValkeyInfoString(dict *section_dict, int all_sections, int everything) { "used_memory_vm_eval:%lld\r\n", memory_lua, "used_memory_lua_human:%s\r\n", used_memory_lua_hmem, /* deprecated */ "used_memory_scripts_eval:%lld\r\n", (long long)mh->lua_caches, - "number_of_cached_scripts:%lu\r\n", dictSize(evalScriptsDict()), + "number_of_cached_scripts:%zu\r\n", dictSize(evalScriptsDict()), "number_of_functions:%lu\r\n", functionsNum(), "number_of_libraries:%lu\r\n", functionsLibNum(), "used_memory_vm_functions:%lld\r\n", memory_functions, @@ -6385,11 +6409,11 @@ sds genValkeyInfoString(dict *section_dict, int all_sections, int everything) { "keyspace_hits:%lld\r\n", server.stat_keyspace_hits, "keyspace_misses:%lld\r\n", server.stat_keyspace_misses, "pubsub_channels:%llu\r\n", kvstoreSize(server.pubsub_channels), - "pubsub_patterns:%lu\r\n", dictSize(server.pubsub_patterns), + "pubsub_patterns:%zu\r\n", dictSize(server.pubsub_patterns), "pubsubshard_channels:%llu\r\n", kvstoreSize(server.pubsubshard_channels), "latest_fork_usec:%lld\r\n", server.stat_fork_time, "total_forks:%lld\r\n", server.stat_total_forks, - "migrate_cached_sockets:%ld\r\n", dictSize(server.migrate_cached_sockets), + "migrate_cached_sockets:%zu\r\n", dictSize(server.migrate_cached_sockets), "slave_expires_tracked_keys:%zu\r\n", getReplicaKeyWithExpireCount(), "active_defrag_hits:%lld\r\n", server.stat_active_defrag_hits, "active_defrag_misses:%lld\r\n", server.stat_active_defrag_misses, @@ -7393,7 +7417,6 @@ __attribute__((weak)) int main(int argc, char **argv) { uint8_t hashseed[16]; getRandomBytes(hashseed, sizeof(hashseed)); - dictSetHashFunctionSeed(hashseed); hashtableSetHashFunctionSeed(hashseed); char *exec_name = strrchr(argv[0], '/'); @@ -7550,10 +7573,15 @@ __attribute__((weak)) int main(int argc, char **argv) { sdsfree(options); } if (server.sentinel_mode) sentinelCheckConfigFile(); - if (server.hash_seed != NULL) { - memset(hashseed, 0, sizeof(hashseed)); - getHashSeedFromString(hashseed, sizeof(hashseed), server.hash_seed); - hashtableSetHashFunctionSeed(hashseed); + + /* Set the configured hash seed used by data hashtables (keys, sets, zsets, + * hashes) or use the random seed if not configured. */ + if (server.hash_seed) { + uint8_t seed[16] = {0}; + getHashSeedFromString(seed, sizeof(seed), server.hash_seed); + setConfigurableHashSeed(seed); + } else { + setConfigurableHashSeed(hashtableGetHashFunctionSeed()); } /* Do system checks */ diff --git a/src/server.h b/src/server.h index b306db549e9..06deb06a84d 100644 --- a/src/server.h +++ b/src/server.h @@ -3907,12 +3907,16 @@ void startEvictionTimeProc(void); /* Keys hashing/comparison functions for dict.c and hashtable.c hash tables. */ uint64_t dictSdsHash(const void *key); uint64_t dictSdsCaseHash(const void *key); +uint64_t dictCStrHash(const void *key); +uint64_t dictCStrCaseHash(const void *key); int dictSdsKeyCompare(const void *key1, const void *key2); -int hashtableSdsKeyCompare(const void *key1, const void *key2); int dictSdsKeyCaseCompare(const void *key1, const void *key2); +int dictCStrKeyCompare(const void *key1, const void *key2); +int dictCStrKeyCaseCompare(const void *key1, const void *key2); void dictSdsDestructor(void *val); void dictListDestructor(void *val); -void *dictSdsDup(const void *key); +void dictEntryDestructorSdsKey(void *entry); +void dictEntryDestructorSdsKeyListValue(void *entry); /* Git SHA1 */ char *serverGitSHA1(void); diff --git a/src/t_zset.c b/src/t_zset.c index a5ab847789c..2ca63ff0f80 100644 --- a/src/t_zset.c +++ b/src/t_zset.c @@ -62,6 +62,7 @@ #include "server.h" #include "intset.h" /* Compact integer set structure */ +#include "mt19937-64.h" #include #include "valkey_strtod.h" diff --git a/src/unit/test_dict.cpp b/src/unit/test_dict.cpp deleted file mode 100644 index b52c3388807..00000000000 --- a/src/unit/test_dict.cpp +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Copyright (c) Valkey Contributors - * All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - */ - -#include "generated_wrappers.hpp" - -#include - -extern "C" { -#include "dict.h" - -extern bool accurate; -/* Wrapper function declarations for accessing static dict.c internals */ -unsigned int testOnlyDictGetForceResizeRatio(void); -signed char testOnlyDictNextExp(unsigned long size); -long long testOnlyTimeInMilliseconds(void); -} - -uint64_t hashCallback(const void *key) { - return dictGenHashFunction((const unsigned char *)key, strlen((const char *)key)); -} - -int compareCallback(const void *key1, const void *key2) { - int l1, l2; - l1 = strlen((const char *)key1); - l2 = strlen((const char *)key2); - if (l1 != l2) return 0; - return memcmp(key1, key2, l1) == 0; -} - -void freeCallback(void *val) { - zfree(val); -} - -char *stringFromLongLong(long long value) { - char buf[32]; - int len; - char *s; - - len = snprintf(buf, sizeof(buf), "%lld", value); - s = (char *)zmalloc(len + 1); - memcpy(s, buf, len); - s[len] = '\0'; - return s; -} - -dictType BenchmarkDictType = {hashCallback, nullptr, compareCallback, freeCallback, nullptr, nullptr}; - -class DictTest : public ::testing::Test { - protected: - dict *_dict = nullptr; - long j; - int retval; - unsigned long new_dict_size, current_dict_used, remain_keys; - - static void SetUpTestSuite() { - monotonicInit(); /* Required for dict tests, that are relying on monotime during dict rehashing. */ - } - - void SetUp() override { - _dict = dictCreate(&BenchmarkDictType); - } - - void TearDown() override { - if (_dict) { - dictRelease(_dict); - _dict = nullptr; - } - /* Restore global resize mode to avoid leaking state across tests. */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - } -}; - -TEST_F(DictTest, dictAdd16Keys) { - /* Add 16 keys and verify dict resize is ok */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - for (j = 0; j < 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - ASSERT_EQ(dictSize(_dict), 16u); - ASSERT_EQ(dictBuckets(_dict), 16u); -} - -TEST_F(DictTest, dictDisableResize) { - /* Use DICT_RESIZE_AVOID to disable the dict resize and pad to (dict_force_resize_ratio * 16) */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - for (j = 0; j < 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - /* Use DICT_RESIZE_AVOID to disable the dict resize, and pad - * the number of keys to (dict_force_resize_ratio * 16), so we can satisfy - * dict_force_resize_ratio in next test. */ - dictSetResizeEnabled(DICT_RESIZE_AVOID); - for (j = 16; j < (long)testOnlyDictGetForceResizeRatio() * 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = testOnlyDictGetForceResizeRatio() * 16; - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(dictBuckets(_dict), 16u); -} - -TEST_F(DictTest, dictAddOneKeyTriggerResize) { - /* Add one more key, trigger the dict resize */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - for (j = 0; j < 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - dictSetResizeEnabled(DICT_RESIZE_AVOID); - for (j = 16; j < (long)testOnlyDictGetForceResizeRatio() * 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = testOnlyDictGetForceResizeRatio() * 16; - - retval = dictAdd(_dict, stringFromLongLong(current_dict_used), (void *)current_dict_used); - ASSERT_EQ(retval, DICT_OK); - current_dict_used++; - new_dict_size = 1UL << testOnlyDictNextExp(current_dict_used); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), 16u); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), new_dict_size); - - /* Wait for rehashing. */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), new_dict_size); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), 0u); -} - -TEST_F(DictTest, dictDeleteKeys) { - /* Delete keys until we can trigger shrink in next test */ - - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - for (j = 0; j < 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - dictSetResizeEnabled(DICT_RESIZE_AVOID); - for (j = 16; j < (long)testOnlyDictGetForceResizeRatio() * 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = testOnlyDictGetForceResizeRatio() * 16; - - retval = dictAdd(_dict, stringFromLongLong(current_dict_used), (void *)current_dict_used); - ASSERT_EQ(retval, DICT_OK); - current_dict_used++; - new_dict_size = 1UL << testOnlyDictNextExp(current_dict_used); - - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - /* Delete keys until we can satisfy (1 / HASHTABLE_MIN_FILL) in the next test. */ - for (j = new_dict_size / HASHTABLE_MIN_FILL + 1; j < (long)current_dict_used; j++) { - char *key = stringFromLongLong(j); - retval = dictDelete(_dict, key); - zfree(key); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = new_dict_size / HASHTABLE_MIN_FILL + 1; - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), new_dict_size); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), 0u); -} - -TEST_F(DictTest, dictDeleteOneKeyTriggerResize) { - /* Delete one more key, trigger the dict resize */ - - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - for (j = 0; j < 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - dictSetResizeEnabled(DICT_RESIZE_AVOID); - for (j = 16; j < (long)testOnlyDictGetForceResizeRatio() * 16; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = testOnlyDictGetForceResizeRatio() * 16; - - retval = dictAdd(_dict, stringFromLongLong(current_dict_used), (void *)current_dict_used); - ASSERT_EQ(retval, DICT_OK); - current_dict_used++; - new_dict_size = 1UL << testOnlyDictNextExp(current_dict_used); - - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - for (j = new_dict_size / HASHTABLE_MIN_FILL + 1; j < (long)current_dict_used; j++) { - char *key = stringFromLongLong(j); - retval = dictDelete(_dict, key); - zfree(key); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = new_dict_size / HASHTABLE_MIN_FILL + 1; - - current_dict_used--; - char *key = stringFromLongLong(current_dict_used); - retval = dictDelete(_dict, key); - zfree(key); - unsigned long oldDictSize = new_dict_size; - new_dict_size = 1UL << testOnlyDictNextExp(current_dict_used); - ASSERT_EQ(retval, DICT_OK); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), oldDictSize); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), new_dict_size); - - /* Wait for rehashing. */ - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), new_dict_size); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), 0u); -} - -TEST_F(DictTest, dictEmptyDirAdd128Keys) { - /* Empty the dictionary and add 128 keys */ - dictEmpty(_dict, nullptr); - for (j = 0; j < 128; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - ASSERT_EQ(dictSize(_dict), 128u); - ASSERT_EQ(dictBuckets(_dict), 128u); -} - -TEST_F(DictTest, dictDisableResizeReduceTo3) { - /* Use DICT_RESIZE_AVOID to disable the dict resize and reduce to 3 */ - - /* Setup: Add 128 keys */ - dictEmpty(_dict, nullptr); - for (j = 0; j < 128; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - /* Use DICT_RESIZE_AVOID to disable the dict reset, and reduce - * the number of keys until we can trigger shrinking in next test. */ - dictSetResizeEnabled(DICT_RESIZE_AVOID); - remain_keys = DICTHT_SIZE(_dict->ht_size_exp[0]) / (HASHTABLE_MIN_FILL * testOnlyDictGetForceResizeRatio()) + 1; - for (j = remain_keys; j < 128; j++) { - char *key = stringFromLongLong(j); - retval = dictDelete(_dict, key); - zfree(key); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = remain_keys; - ASSERT_EQ(dictSize(_dict), remain_keys); - ASSERT_EQ(dictBuckets(_dict), 128u); -} - -TEST_F(DictTest, dictDeleteOneKeyTriggerResizeAgain) { - /* Delete one more key, trigger the dict resize */ - - /* Setup: Add 128 keys and reduce */ - dictEmpty(_dict, nullptr); - dictSetResizeEnabled(DICT_RESIZE_ENABLE); /* Reset resize mode before adding keys */ - for (j = 0; j < 128; j++) { - retval = dictAdd(_dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - - dictSetResizeEnabled(DICT_RESIZE_AVOID); - remain_keys = DICTHT_SIZE(_dict->ht_size_exp[0]) / (HASHTABLE_MIN_FILL * testOnlyDictGetForceResizeRatio()) + 1; - for (j = remain_keys; j < 128; j++) { - char *key = stringFromLongLong(j); - retval = dictDelete(_dict, key); - zfree(key); - ASSERT_EQ(retval, DICT_OK); - } - current_dict_used = remain_keys; - - current_dict_used--; - char *key = stringFromLongLong(current_dict_used); - retval = dictDelete(_dict, key); - zfree(key); - new_dict_size = 1UL << testOnlyDictNextExp(current_dict_used); - ASSERT_EQ(retval, DICT_OK); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), 128u); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), new_dict_size); - - /* Wait for rehashing. */ - dictSetResizeEnabled(DICT_RESIZE_ENABLE); - while (dictIsRehashing(_dict)) dictRehashMicroseconds(_dict, 1000); - ASSERT_EQ(dictSize(_dict), current_dict_used); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[0]), new_dict_size); - ASSERT_EQ(DICTHT_SIZE(_dict->ht_size_exp[1]), 0u); -} - -/* This is a benchmark test for dict performance. - * To run this test explicitly, use: - * ./src/unit/valkey-unit-gtests --gtest_filter=DictTest.DISABLED_dictBenchmark --gtest_also_run_disabled_tests - */ -TEST_F(DictTest, DISABLED_dictBenchmark) { - long j; - long long start, elapsed; - int retval; - dict *dict = dictCreate(&BenchmarkDictType); - long count = accurate ? 5000000 : 5000; - -#define start_benchmark() start = testOnlyTimeInMilliseconds() -#define end_benchmark(msg) \ - do { \ - elapsed = testOnlyTimeInMilliseconds() - start; \ - printf(msg ": %ld items in %lld ms\n", count, elapsed); \ - } while (0) - - start_benchmark(); - for (j = 0; j < count; j++) { - retval = dictAdd(dict, stringFromLongLong(j), (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - end_benchmark("Inserting"); - ASSERT_EQ((long)dictSize(dict), count); - - /* Wait for rehashing. */ - while (dictIsRehashing(dict)) { - dictRehashMicroseconds(dict, 100 * 1000); - } - - start_benchmark(); - for (j = 0; j < count; j++) { - char *key = stringFromLongLong(j); - dictEntry *de = dictFind(dict, key); - ASSERT_NE(de, nullptr); - zfree(key); - } - end_benchmark("Linear access of existing elements"); - - start_benchmark(); - for (j = 0; j < count; j++) { - char *key = stringFromLongLong(j); - dictEntry *de = dictFind(dict, key); - ASSERT_NE(de, nullptr); - zfree(key); - } - end_benchmark("Linear access of existing elements (2nd round)"); - - start_benchmark(); - for (j = 0; j < count; j++) { - char *key = stringFromLongLong(rand() % count); - dictEntry *de = dictFind(dict, key); - ASSERT_NE(de, nullptr); - zfree(key); - } - end_benchmark("Random access of existing elements"); - - start_benchmark(); - for (j = 0; j < count; j++) { - dictEntry *de = dictGetRandomKey(dict); - ASSERT_NE(de, nullptr); - } - end_benchmark("Accessing random keys"); - - start_benchmark(); - for (j = 0; j < count; j++) { - char *key = stringFromLongLong(rand() % count); - key[0] = 'X'; - dictEntry *de = dictFind(dict, key); - ASSERT_EQ(de, nullptr); - zfree(key); - } - end_benchmark("Accessing missing"); - - start_benchmark(); - for (j = 0; j < count; j++) { - char *key = stringFromLongLong(j); - retval = dictDelete(dict, key); - ASSERT_EQ(retval, DICT_OK); - key[0] += 17; /* Change first number to letter. */ - retval = dictAdd(dict, key, (void *)j); - ASSERT_EQ(retval, DICT_OK); - } - end_benchmark("Removing and adding"); - dictRelease(dict); - -#undef start_benchmark -#undef end_benchmark -} diff --git a/src/unit/test_hashtable.cpp b/src/unit/test_hashtable.cpp index e58e257f92d..17b026f3f3b 100644 --- a/src/unit/test_hashtable.cpp +++ b/src/unit/test_hashtable.cpp @@ -72,7 +72,7 @@ static uint64_t hashfunc(const void *key) { } static int keycmp(const void *key1, const void *key2) { - return strcmp((const char *)key1, (const char *)key2); + return strcmp((const char *)key1, (const char *)key2) == 0; } static void freekeyval(void *keyval) { diff --git a/src/unit/test_kvstore.cpp b/src/unit/test_kvstore.cpp index 2dbace519da..0c0ac1584ab 100644 --- a/src/unit/test_kvstore.cpp +++ b/src/unit/test_kvstore.cpp @@ -20,7 +20,7 @@ uint64_t hashConflictTestCallback(const void *key) { } int cmpTestCallback(const void *k1, const void *k2) { - return strcmp((const char *)k1, (const char *)k2); + return strcmp((const char *)k1, (const char *)k2) == 0; } void freeTestCallback(void *val) { diff --git a/src/valkey-benchmark.c b/src/valkey-benchmark.c index a0738414a08..aa1d4772530 100644 --- a/src/valkey-benchmark.c +++ b/src/valkey-benchmark.c @@ -279,7 +279,7 @@ static bool isBenchmarkFinished(int request_count) { } static uint64_t dictSdsHash(const void *key) { - return dictGenHashFunction((unsigned char *)key, sdslen((char *)key)); + return dictGenHashFunction(key, sdslen(key)); } static int dictSdsKeyCompare(const void *key1, const void *key2) { @@ -291,12 +291,10 @@ static int dictSdsKeyCompare(const void *key1, const void *key2) { } static dictType dtype = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - NULL, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = zfree, }; static valkeyContext *getValkeyContext(enum valkeyConnectionType ct, const char *ip_or_path, int port) { diff --git a/src/valkey-cli.c b/src/valkey-cli.c index 034fb0cfbeb..d01002780a8 100644 --- a/src/valkey-cli.c +++ b/src/valkey-cli.c @@ -190,8 +190,6 @@ static struct termios orig_termios; /* To restore terminal at exit.*/ /* Dict Helpers */ static uint64_t dictSdsHash(const void *key); static int dictSdsKeyCompare(const void *key1, const void *key2); -static void dictSdsDestructor(void *val); -static void dictListDestructor(void *val); /* Cluster Manager Command Info */ typedef struct clusterManagerCommand { @@ -379,7 +377,7 @@ static sds getDotfilePath(char *envoverride, char *envoverride_old, char *dotfil } static uint64_t dictSdsHash(const void *key) { - return dictGenHashFunction((unsigned char *)key, sdslen((char *)key)); + return dictGenHashFunction(key, sdslen(key)); } static int dictSdsKeyCompare(const void *key1, const void *key2) { @@ -390,12 +388,23 @@ static int dictSdsKeyCompare(const void *key1, const void *key2) { return memcmp(key1, key2, l1) == 0; } -static void dictSdsDestructor(void *val) { - sdsfree(val); +static void dictEntryDestructorSdsKeyNoVal(void *entry) { + dictEntry *de = entry; + sdsfree(dictGetKey(de)); + zfree(de); } -void dictListDestructor(void *val) { - listRelease((list *)val); +static void dictEntryDestructorSdsVal(void *entry) { + dictEntry *de = entry; + sdsfree(dictGetVal(de)); + zfree(de); +} + +static void dictEntryDestructorSdsKeyListVal(void *entry) { + dictEntry *de = entry; + sdsfree(dictGetKey(de)); + listRelease(dictGetVal(de)); + zfree(de); } /*------------------------------------------------------------------------------ @@ -890,12 +899,10 @@ static void cliLegacyInitHelp(dict *groups) { static void cliInitHelp(void) { /* Dict type for a set of strings, used to collect names of command groups. */ dictType groupsdt = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - NULL, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyNoVal, }; valkeyReply *commandTable; dict *groups; @@ -3661,21 +3668,17 @@ typedef struct clusterManagerLink { } clusterManagerLink; static dictType clusterManagerDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - NULL, /* key destructor */ - dictSdsDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsVal, }; static dictType clusterManagerLinkDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - dictSdsDestructor, /* key destructor */ - dictListDestructor, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorSdsKeyListVal, }; typedef int clusterManagerCommandProc(int argc, char **argv); @@ -9163,13 +9166,17 @@ void type_free(void *val) { zfree(info); } +static void dictEntryDestructorTypeinfoVal(void *entry) { + dictEntry *de = entry; + type_free(dictGetVal(de)); + zfree(de); +} + static dictType typeinfoDictType = { - dictSdsHash, /* hash function */ - NULL, /* key dup */ - dictSdsKeyCompare, /* key compare */ - NULL, /* key destructor (owned by the value)*/ - type_free, /* val destructor */ - NULL /* allow to expand */ + .entryGetKey = dictEntryGetKey, + .hashFunction = dictSdsHash, + .keyCompare = dictSdsKeyCompare, + .entryDestructor = dictEntryDestructorTypeinfoVal, }; static void getKeyTypes(dict *types_dict, valkeyReply *keys, typeinfo **types) {