2 This is used for quick userlist insertion and lookup. It's not really
3 a tree, but it could be :)
24 tree_new (tree_cmp_func
*cmp
, void *data
)
26 tree
*t
= calloc (1, sizeof (tree
));
33 tree_destroy (tree
*t
)
44 tree_find_insertion_pos (tree
*t
, void *key
, int *done
)
59 c
= t
->cmp (key
, t
->array
[0], t
->data
);
68 t
->array
[1] = t
->array
[0];
75 c
= t
->cmp (key
, t
->array
[0], t
->data
);
77 return 0; /* prepend */
79 c
= t
->cmp (key
, t
->array
[t
->elements
- 1], t
->data
);
81 return t
->elements
; /* append */
88 c
= t
->cmp (key
, t
->array
[idx
], t
->data
);
92 else if (0 < c
&& 0 > t
->cmp (key
, t
->array
[idx
+1], t
->data
))
102 tree_insert_at_pos (tree
*t
, void *key
, int pos
)
107 if (pos
!= t
->elements
)
109 post_bytes
= (t
->elements
- pos
) * sizeof (void *);
110 memmove (&t
->array
[pos
+ 1], &t
->array
[pos
], post_bytes
);
118 mybsearch (const void *key
, void **array
, size_t nmemb
,
119 int (*compar
) (const void *, const void *, void *data
), void *data
, int *pos
)
129 comparison
= (*compar
) (key
, array
[idx
], data
);
132 else if (comparison
> 0)
145 tree_find (tree
*t
, void *key
, tree_cmp_func
*cmp
, void *data
, int *pos
)
150 return mybsearch (key
, &t
->array
[0], t
->elements
, cmp
, data
, pos
);
154 tree_remove_at_pos (tree
*t
, int pos
)
159 if (pos
!= t
->elements
)
161 post_bytes
= (t
->elements
- pos
) * sizeof (void *);
162 memmove (&t
->array
[pos
], &t
->array
[pos
+ 1], post_bytes
);
167 tree_remove (tree
*t
, void *key
, int *pos
)
171 data
= tree_find (t
, key
, t
->cmp
, t
->data
, pos
);
175 tree_remove_at_pos (t
, *pos
);
180 tree_foreach (tree
*t
, tree_traverse_func
*func
, void *data
)
187 for (j
= 0; j
< t
->elements
; j
++)
189 if (!func (t
->array
[j
], data
))
197 if (t
->array_size
< t
->elements
+ 1)
199 int new_size
= t
->array_size
+ ARRAY_GROW
;
201 t
->array
= realloc (t
->array
, sizeof (void *) * new_size
);
202 t
->array_size
= new_size
;
208 tree_insert (tree
*t
, void *key
)
216 pos
= tree_find_insertion_pos (t
, key
, &done
);
217 if (!done
&& pos
!= -1)
218 tree_insert_at_pos (t
, key
, pos
);
224 tree_append (tree
*t
, void *key
)
227 tree_insert_at_pos (t
, key
, t
->elements
);
230 int tree_size (tree
*t
)