summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid McMackins II <contact@mcmackins.org>2020-02-25 21:13:37 -0600
committerDavid McMackins II <contact@mcmackins.org>2020-02-25 21:23:18 -0600
commit3853f385d261626791f3cf397ed4806d920590da (patch)
treea1c8070dd4e54d01632bdb319a3539edaf17cc7f
parent3c1f28a7bf0d7c3335c1cf25d664596a21eb22b0 (diff)
Add pt_copy
-rw-r--r--Makefile2
-rw-r--r--pfxtree-test.c9
-rw-r--r--pfxtree.c30
-rw-r--r--pfxtree.h8
4 files changed, 45 insertions, 4 deletions
diff --git a/Makefile b/Makefile
index 2b0bcdd..5790896 100644
--- a/Makefile
+++ b/Makefile
@@ -8,7 +8,7 @@ PKGCONFIGDIR=$(LIBDIR)/pkgconfig
HDIR=$(DESTDIR)$(PREFIX)/include
MAJOR=0
-MINOR=3
+MINOR=4
REVISION=0
VERSION=$(MAJOR).$(MINOR).$(REVISION)
diff --git a/pfxtree-test.c b/pfxtree-test.c
index 345b7bc..acabca9 100644
--- a/pfxtree-test.c
+++ b/pfxtree-test.c
@@ -55,7 +55,7 @@ check_entry(const struct pt_entry *entry, void *data)
int
main(void)
{
- PrefixTree *p = pt_new();
+ PrefixTree *p = pt_new(), *p2;
void *dummy;
assert(p != NULL);
@@ -71,7 +71,7 @@ main(void)
assert(NULL == pt_search(p, "hello"));
assert(pt_search(p, "hell") != NULL);
- dummy = malloc(0xDFDF);
+ dummy = malloc(16);
assert(dummy != NULL);
assert(0 == pt_add_p(p, "hello", dummy));
assert(PT_TYPE_PTR == pt_data_type(pt_search(p, "hello")));
@@ -80,6 +80,11 @@ main(void)
pt_foreach(p, check_entry, dummy);
+ p2 = pt_copy(p);
+ assert(p2 != NULL);
+ assert(pt_data_p(pt_search(p2, "hello")) == dummy);
+
pt_deep_free(p, true);
+ pt_deep_free(p2, false);
return 0;
}
diff --git a/pfxtree.c b/pfxtree.c
index c295ada..0560184 100644
--- a/pfxtree.c
+++ b/pfxtree.c
@@ -61,6 +61,34 @@ pt_new()
return self;
}
+static int
+copy(const struct pt_entry *entry, void *data)
+{
+ PrefixTree *tree = (PrefixTree *) data;
+ const char *word = entry->word;
+
+ if (entry->type == PT_TYPE_INT)
+ return pt_add(tree, word, entry->data.i);
+
+ return pt_add_p(tree, word, entry->data.p);
+}
+
+PrefixTree *
+pt_copy(const PrefixTree *src)
+{
+ PrefixTree *new = pt_new();
+ if (!new)
+ return NULL;
+
+ if (pt_foreach(src, copy, new))
+ {
+ pt_free(new);
+ return NULL;
+ }
+
+ return new;
+}
+
void
pt_free(PrefixTree *self)
{
@@ -355,5 +383,5 @@ end:
const char *
pt_version()
{
- return "0.3.0";
+ return "0.4.0";
}
diff --git a/pfxtree.h b/pfxtree.h
index 7e1614f..70d9326 100644
--- a/pfxtree.h
+++ b/pfxtree.h
@@ -103,6 +103,14 @@ PrefixTree *
pt_new(void);
/**
+ * @brief Copies a prefix tree.
+ * @param src The prefix tree to be copied.
+ * @return The copied tree, or NULL on failure.
+ */
+PrefixTree *
+pt_copy(const PrefixTree *src);
+
+/**
* @brief Frees an allocated prefix tree (and its child nodes).
* @param self The tree to free.
*/