]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
lib/generic/trie: add trie_apply_with_key()
authorVladimír Čunát <vladimir.cunat@nic.cz>
Thu, 28 Apr 2022 11:32:52 +0000 (13:32 +0200)
committerOto Šťáva <oto.stava@nic.cz>
Wed, 11 May 2022 06:02:19 +0000 (08:02 +0200)
lib/generic/trie.c
lib/generic/trie.h

index 2a666092c325077e2924ecf6c09661f8266ee7d7..51a37b93fee5281c2517b3e108b84eeecb8ff2bc 100644 (file)
@@ -843,6 +843,26 @@ int trie_apply(trie_t *tbl, int (*f)(trie_val_t *, void *), void *d)
        return apply_trie(&tbl->root, f, d);
 }
 
+/*! \brief Apply a function to every key + trie_val_t*, in order; a recursive solution. */
+static int apply_trie_with_key(node_t *t, int (*f)(const char *, uint32_t, trie_val_t *, void *), void *d)
+{
+       kr_require(t);
+       if (!isbranch(t))
+               return f(t->leaf.key->chars, t->leaf.key->len, &t->leaf.val, d);
+       int child_count = bitmap_weight(t->branch.bitmap);
+       for (int i = 0; i < child_count; ++i)
+               ERR_RETURN(apply_trie_with_key(twig(t, i), f, d));
+       return KNOT_EOK;
+}
+
+int trie_apply_with_key(trie_t *tbl, int (*f)(const char *, uint32_t, trie_val_t *, void *), void *d)
+{
+       kr_require(tbl && f);
+       if (!tbl->weight)
+               return KNOT_EOK;
+       return apply_trie_with_key(&tbl->root, f, d);
+}
+
 /* These are all thin wrappers around static Tns* functions. */
 trie_it_t* trie_it_begin(trie_t *tbl)
 {
index e32b89b6a08bda7159b3b8f1775c89c19a1f6752..8c4429767c826d586e7c188842e69c9d53a978ba 100644 (file)
@@ -83,6 +83,17 @@ int trie_get_leq(trie_t *tbl, const char *key, uint32_t len, trie_val_t **val);
 KR_EXPORT
 int trie_apply(trie_t *tbl, int (*f)(trie_val_t *, void *), void *d);
 
+/*!
+ * \brief Apply a function to every trie_val_t, in order.
+ *
+ * It's like trie_apply() but additionally passes keys and their lengths.
+ *
+ * \param d Parameter passed as the second argument to f().
+ * \return First nonzero from f() or zero (i.e. KNOT_EOK).
+ */
+KR_EXPORT
+int trie_apply_with_key(trie_t *tbl, int (*f)(const char *, uint32_t, trie_val_t *, void *), void *d);
+
 /*!
  * \brief Remove an item, returning KNOT_EOK if succeeded or KNOT_ENOENT if not found.
  *