diff mbox

[24/28] add a tree function to return a list of elements

Message ID 1308256197-29155-24-git-send-email-daniel.lezcano@linaro.org
State Accepted
Headers show

Commit Message

Daniel Lezcano June 16, 2011, 8:29 p.m. UTC
This patch provides a function returning all the node of the tree
matching the substring passed a parameter.

Signed-off-by: Daniel Lezcano <daniel.lezcano@linaro.org>
---
 tree.c |   48 ++++++++++++++++++++++++++++++++++++++++++++++++
 tree.h |    2 ++
 2 files changed, 50 insertions(+), 0 deletions(-)
diff mbox

Patch

diff --git a/tree.c b/tree.c
index 516e832..8f546a9 100644
--- a/tree.c
+++ b/tree.c
@@ -265,3 +265,51 @@  struct tree *tree_find(struct tree *tree, const char *name)
 
 	return tree_find(tree->next, name);
 }
+
+struct struct_find {
+	int nr;
+	const char *name;
+	struct tree ***ptree;
+};
+
+static int tree_finds_cb(struct tree *tree, void *data)
+{
+	struct struct_find *sf = data;
+
+	if (strncmp(sf->name, tree->name, strlen(sf->name)))
+		return 0;
+
+	if (sf->ptree)
+		(*(sf->ptree))[sf->nr] = tree;
+
+	sf->nr++;
+
+	return 0;
+}
+
+int tree_finds(struct tree *tree, const char *name, struct tree ***ptr)
+{
+	struct struct_find sf = { .nr = 0, .ptree = NULL, .name = name };
+	int nmatch;
+
+	/* first pass : count # of matching nodes */
+	tree_for_each(tree, tree_finds_cb, &sf);
+
+	/* no match */
+	if (!sf.nr)
+		return 0;
+
+	*ptr = malloc(sizeof(struct tree *) * sf.nr);
+	if (!*ptr)
+		return -1;
+
+	/* store the result as it will be overwritten by the next call */
+	nmatch = sf.nr;
+	sf.nr = 0;
+	sf.ptree = ptr;
+
+	/* second pass : fill with the matching nodes */
+	tree_for_each(tree, tree_finds_cb, &sf);
+
+	return nmatch;
+}
diff --git a/tree.h b/tree.h
index 2af4a5a..88d4a19 100644
--- a/tree.h
+++ b/tree.h
@@ -49,3 +49,5 @@  extern int tree_for_each(struct tree *tree, tree_cb_t cb, void *data);
 extern int tree_for_each_reverse(struct tree *tree, tree_cb_t cb, void *data);
 
 extern int tree_for_each_parent(struct tree *tree, tree_cb_t cb, void *data);
+
+extern int tree_finds(struct tree *tree, const char *name, struct tree ***ptr);