-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathnamed.c
65 lines (55 loc) · 1.6 KB
/
named.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
typedef struct _Named {
struct _Named *next;
char *name;
void *data;
} Named;
void *find_by_name (void *l, char *name);
void *get_by_name (void *l, char *name, int size);
Named *named_insert (Named *l, char *name, void *data);
void *_named_insert_sorted (void *h, void *x);
void *named_insert_sorted (void *head, char *name, void *data);
int find_index_by_name (void *l, char *name);
#ifndef HEADER_ONLY
void *find_by_name (void *l, char *name) {
Named *list = l;
while (list) {
if (list->name && strcmp (list->name, name) == 0) return list;
list = list->next;
} return NULL;
}
void *get_by_name (void *l, char *name, int size) {
Named **list = l, *n = find_by_name (*list, name);
if (!n) {
n = calloc (1, size);
n->name = strdup (name);
n->next = *list; *list = n;
} return n;
}
Named *named_insert (Named *l, char *name, void *data) {
Named *n = malloc (sizeof (Named));
n->next = l;
n->name = name;
n->data = data;
return n;
}
void *_named_insert_sorted (void *h, void *x) {
Named *prev = NULL, *head = h, *n = x, *l = head;
while (l && (strcmp (n->name, l->name) > 0)) {
prev = l; l = l->next;
}
if (prev) { prev->next = n; n->next = l; }
else { n->next = head; head = n; }
return head;
}
void *named_insert_sorted (void *head, char *name, void *data) {
Named *n = named_insert (NULL, name, data);
return _named_insert_sorted (head, n);
}
int find_index_by_name (void *l, char *name) {
Named *list = (Named *)l; int i = 0;
while (list) {
if (list->name && strcmp (list->name, name) == 0) return i;
list = list->next; i++;
} return -1;
}
#endif