0f62b864b50f9bf4d28020dd7caa35446dc85449
[fw/openocd] / contrib / list_example.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /* Copyright (C) 2021 by Andreas Fritiofson <andreas.fritiofson@gmail.com> */
3
4 /*
5  * Simple example of using a circular doubly linked list through list.h
6  *
7  * gcc -I ../src/ list_example.c -o list_example
8  */
9
10 #include <stdint.h>
11 #include <stdbool.h>
12 #include <assert.h>
13 #include <helper/list.h>
14
15 static LIST_HEAD(threads);
16
17 struct thread {
18         int id;
19         uint64_t tcb_address;
20         struct list_head lh;
21 };
22
23 void insert(struct thread *t)
24 {
25         list_add_tail(&t->lh, &threads);
26 }
27
28 void remove(struct thread *t)
29 {
30         list_del(&t->lh);
31 }
32
33 struct thread *lookup_id(int id)
34 {
35         struct thread *t;
36         list_for_each_entry(t, &threads, lh) {
37                 if (t->id == id)
38                         return t;
39         }
40         return NULL;
41 }
42
43 struct thread *lookup_tcb(uint64_t addr)
44 {
45         struct thread *t;
46         list_for_each_entry(t, &threads, lh) {
47                 if (t->tcb_address == addr)
48                         return t;
49         }
50         return NULL;
51 }
52
53 int main(void)
54 {
55         struct thread t1 = { .id = 1, .tcb_address = 111111111 };
56         struct thread t2 = { .id = 2, .tcb_address = 222222222 };
57         struct thread t3 = { .id = 3, .tcb_address = 333333333 };
58
59         insert(&t1);
60         insert(&t2);
61         assert(lookup_id(1) == &t1);
62         assert(lookup_tcb(111111111) == &t1);
63         assert(lookup_id(2) == &t2);
64         assert(lookup_id(42) == NULL);
65         remove(&t1);
66         assert(lookup_id(1) == NULL);
67         insert(&t3);
68         remove(&t2);
69         assert(lookup_id(3) == &t3);
70         assert(lookup_tcb(333333333) == &t3);
71         assert(lookup_id(2) == NULL);
72         remove(&t3);
73         assert(list_empty(&threads));
74 }