From 5b1ebed3fc4a08b7d59f4bb086856fbb8d164117 Mon Sep 17 00:00:00 2001 From: Zdenek Kabelac Date: Thu, 24 Oct 2024 14:04:07 +0200 Subject: [PATCH] radix_tree: add radix_tree_uniq_insert When using radix_tree to identify duplicate entries we may avoid to call an extra 'lookup()' prior the insert() operation add radix_tree_uniq_insert/_ptr() that is able to report -1 if there was already set a value for the given key. --- base/data-struct/radix-tree-adaptive.c | 7 +++++++ base/data-struct/radix-tree.h | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/base/data-struct/radix-tree-adaptive.c b/base/data-struct/radix-tree-adaptive.c index fcd333bb1..69984e66a 100644 --- a/base/data-struct/radix-tree-adaptive.c +++ b/base/data-struct/radix-tree-adaptive.c @@ -564,6 +564,13 @@ bool radix_tree_insert(struct radix_tree *rt, const void *key, size_t keylen, un return _insert(rt, lr.v, lr.kb, ke, rv); } +int radix_tree_uniq_insert(struct radix_tree *rt, const void *key, size_t keylen, union radix_value rv) +{ + unsigned entries = rt->nr_entries; + return radix_tree_insert(rt, key, keylen, rv) ? + ((entries != rt->nr_entries) ? 1 : -1) : 0; +} + // Note the degrade functions also free the original node. static void _degrade_to_n4(struct node16 *n16, struct value *result) { diff --git a/base/data-struct/radix-tree.h b/base/data-struct/radix-tree.h index b41105652..f0fe2baf3 100644 --- a/base/data-struct/radix-tree.h +++ b/base/data-struct/radix-tree.h @@ -35,6 +35,10 @@ void radix_tree_destroy(struct radix_tree *rt); unsigned radix_tree_size(struct radix_tree *rt); bool radix_tree_insert(struct radix_tree *rt, const void *key, size_t keylen, union radix_value v); bool radix_tree_remove(struct radix_tree *rt, const void *key, size_t keylen); +// Returns: 1 success +// 0 failure during insert +// -1 key had already existing value (that was updated) +int radix_tree_uniq_insert(struct radix_tree *rt, const void *key, size_t keylen, union radix_value v); // Returns the number of values removed unsigned radix_tree_remove_prefix(struct radix_tree *rt, const void *prefix, size_t prefix_len); @@ -78,6 +82,12 @@ static inline bool radix_tree_insert_ptr(struct radix_tree *rt, const void *key, union radix_value v = { .ptr = ptr }; return radix_tree_insert(rt, key, keylen, v); } + +static inline int radix_tree_uniq_insert_ptr(struct radix_tree *rt, const void *key, size_t keylen, void *ptr) +{ + union radix_value v = { .ptr = ptr }; + return radix_tree_uniq_insert(rt, key, keylen, v); +} //---------------------------------------------------------------- #endif