From 3853f385d261626791f3cf397ed4806d920590da Mon Sep 17 00:00:00 2001 From: David McMackins II Date: Tue, 25 Feb 2020 21:13:37 -0600 Subject: Add pt_copy --- Makefile | 2 +- pfxtree-test.c | 9 +++++++-- pfxtree.c | 30 +++++++++++++++++++++++++++++- pfxtree.h | 8 ++++++++ 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 @@ -102,6 +102,14 @@ typedef struct _pt_trie 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. -- cgit v1.2.3