Root/qpkg/id.c

Source at commit a9f12d56661a8e6def5a2b32519c3efd55e38d31 created 8 years 10 months ago.
By Werner Almesberger, qpkg: converted ID comparison from "struct id *" to "void *"
1#include <string.h>
2
3#include "util.h"
4#include "id.h"
5
6
7static struct id *free_id = NULL;
8
9
10static int do_comp_id(const struct id *a, const struct id *b)
11{
12    int len = a->len < b->len ? a->len : b->len;
13    int cmp;
14
15    cmp = memcmp(a->s, b->s, len);
16    if (cmp)
17        return cmp;
18    return a->len < b->len ? -1 : a->len > b->len;
19}
20
21
22int comp_id(const void *a, const void *b)
23{
24    return do_comp_id(a, b);
25}
26
27struct tree *make_tree(int (*comp)(const void *a, const void *b))
28{
29    struct tree *tree;
30
31    tree = alloc_type(struct tree);
32    tree->comp = comp;
33    tree->root = make_jrb();
34    return tree;
35}
36
37
38struct id *make_id(struct tree *tree, const char *s, size_t len)
39{
40    struct id *id;
41    struct jrb *node;
42
43    if (!free_id)
44        free_id = alloc_type(struct id);
45    id = free_id;
46    id->s = s;
47    id->len = len;
48    id->value = NULL;
49    node = jrb_find(tree->root, id, tree->comp);
50    if (node)
51        return node->key;
52    id->jrb = jrb_insert(tree->root, id, NULL, tree->comp);
53    free_id = NULL;
54    return id;
55}
56
57
58const struct id *find_id(const struct tree *tree, const char *s, size_t len)
59{
60    struct id id = {
61        .s = s,
62        .len = len
63    };
64    struct jrb *node;
65
66    node = jrb_find(tree->root, &id, tree->comp);
67    return node ? node->key : NULL;
68}
69
70
71const struct id *first_id(const struct tree *tree)
72{
73    struct jrb *node;
74
75    node = jrb_first(tree->root);
76    return node ? node->key : NULL;
77}
78
79
80const struct id *next_id(const struct id *id)
81{
82    struct jrb *next;
83
84    next = jrb_next(id->jrb);
85    return next ? next->key : NULL;
86}
87

Archive Download this file

Branches:
master



interactive