OSDN Git Service

Initial import from mingw-utils-0.3
[mingw/pexports.git] / str_tree.c
1 #include <string.h>
2
3 #include "str_tree.h"
4
5 static str_tree *new_leaf(const char *s, void *extra)
6 {
7   str_tree *leaf;
8   leaf = (str_tree *) malloc(sizeof(str_tree));
9   if (!leaf)
10     return NULL;
11   leaf->s = strdup(s);
12   if (!leaf->s)
13     {
14       free(leaf);
15       return NULL;
16     }
17   leaf->extra = extra;
18   leaf->left = leaf->right = NULL;
19   return leaf;
20 }
21 str_tree *str_tree_add(str_tree **root, const char *s, void *extra)
22 {
23   if (!*root)
24     return (*root = new_leaf(s, extra));
25   else if (strcmp(s, (*root)->s) < 0)
26     return str_tree_add(&(*root)->left, s, extra);
27   else
28     return str_tree_add(&(*root)->right, s, extra);
29 }
30
31 str_tree *str_tree_find(str_tree *node, const char *s)
32 {
33   if (node == NULL)
34     return NULL;
35   if (strcmp(s, node->s) == 0)
36     return node;
37   else if (strcmp(s, node->s) < 0)
38     return str_tree_find(node->left, s);
39   else
40     return str_tree_find(node->right, s);
41 }
42
43 void str_tree_free(str_tree **root)
44 {
45   if (*root)
46     {
47       str_tree *node = *root;
48       free(node->s);
49       str_tree_free(&node->left);
50       str_tree_free(&node->right);
51       free(node);
52       *root = NULL;
53     }
54 }
55
56 int str_tree_traverse(str_tree *root,int(*f)(str_tree *node))
57 {
58   if (root == NULL)   return 1;
59
60   if (!str_tree_traverse(root->left,f) ||
61       !f(root) ||
62       !str_tree_traverse(root->right,f)) return 0;
63   return 1;
64 }