mirror of
git://projects.qi-hardware.com/wernermisc.git
synced 2024-11-22 12:05:54 +02:00
03c5e4ffe7
- jrb.h, jrb.c (jrb_find_or_insert): new function to look for a node and to insert a new one if not found - id.c (make_id): use jrb_find_or_insert to avoid looking up new nodes twice - TODO: report the improvement
84 lines
1.4 KiB
C
84 lines
1.4 KiB
C
#include <string.h>
|
|
|
|
#include "util.h"
|
|
#include "id.h"
|
|
|
|
|
|
static struct id *free_id = NULL;
|
|
|
|
|
|
static int do_comp_id(const struct id *a, const struct id *b)
|
|
{
|
|
int len = a->len < b->len ? a->len : b->len;
|
|
int cmp;
|
|
|
|
cmp = memcmp(a->s, b->s, len);
|
|
if (cmp)
|
|
return cmp;
|
|
return a->len < b->len ? -1 : a->len > b->len;
|
|
}
|
|
|
|
|
|
int comp_id(const void *a, const void *b)
|
|
{
|
|
return do_comp_id(a, b);
|
|
}
|
|
|
|
struct tree *make_tree(int (*comp)(const void *a, const void *b))
|
|
{
|
|
struct tree *tree;
|
|
|
|
tree = alloc_type(struct tree);
|
|
tree->comp = comp;
|
|
tree->root = make_jrb();
|
|
return tree;
|
|
}
|
|
|
|
|
|
struct id *make_id(struct tree *tree, const char *s, size_t len)
|
|
{
|
|
struct id *id;
|
|
|
|
if (!free_id)
|
|
free_id = alloc_type(struct id);
|
|
id = free_id;
|
|
id->s = s;
|
|
id->len = len;
|
|
id->jrb = jrb_find_or_insert(tree->root, id, NULL, tree->comp);
|
|
if (id->jrb->key != id)
|
|
return id->jrb->key;
|
|
free_id = NULL;
|
|
return id;
|
|
}
|
|
|
|
|
|
const struct id *find_id(const struct tree *tree, const char *s, size_t len)
|
|
{
|
|
struct id id = {
|
|
.s = s,
|
|
.len = len
|
|
};
|
|
struct jrb *node;
|
|
|
|
node = jrb_find(tree->root, &id, tree->comp);
|
|
return node ? node->key : NULL;
|
|
}
|
|
|
|
|
|
const struct id *first_id(const struct tree *tree)
|
|
{
|
|
struct jrb *node;
|
|
|
|
node = jrb_first(tree->root);
|
|
return node ? node->key : NULL;
|
|
}
|
|
|
|
|
|
const struct id *next_id(const struct id *id)
|
|
{
|
|
struct jrb *next;
|
|
|
|
next = jrb_next(id->jrb);
|
|
return next ? next->key : NULL;
|
|
}
|