summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/intrusive.c
diff options
context:
space:
mode:
authorTyge Lovset <[email protected]>2022-12-20 23:31:51 +0100
committerTyge Lovset <[email protected]>2022-12-20 23:31:51 +0100
commit5f57d597cd27aef55adbcb3b452973b0c6e33667 (patch)
treedfd59c2fd0e36a6ef37912a9d0cc5a65970f1524 /misc/examples/intrusive.c
parent1763be8c8cbbc0896477fcf924edd4180d1345a9 (diff)
downloadSTC-modified-5f57d597cd27aef55adbcb3b452973b0c6e33667.tar.gz
STC-modified-5f57d597cd27aef55adbcb3b452973b0c6e33667.zip
Restructured folders: examples, benchmarks, tests into misc folder.
Diffstat (limited to 'misc/examples/intrusive.c')
-rw-r--r--misc/examples/intrusive.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/misc/examples/intrusive.c b/misc/examples/intrusive.c
new file mode 100644
index 00000000..acf4416d
--- /dev/null
+++ b/misc/examples/intrusive.c
@@ -0,0 +1,52 @@
+// Example of intrusive list by using the node API and typesafe c_container_of().
+
+#include <stdio.h>
+
+#define i_type List1
+#define i_val int
+#define i_extern // implement List1_sort()
+#include <stc/clist.h>
+
+#define i_type List2
+#define i_val List1_node
+#define i_opt c_no_cmp // no elem. comparison
+#include <stc/clist.h>
+
+int main()
+{
+ c_auto (List2, list2)
+ {
+ List1 list1 = List1_init(); // should not be destroyed, list2 will destroy shared nodes.
+
+ c_forlist (i, int, {6, 9, 3, 1, 7, 4, 5, 2, 8})
+ List2_push_back(&list2, (List1_node){NULL, *i.ref});
+
+ c_foreach (i, List2, list2)
+ List1_push_node_back(&list1, c_container_of(&i.ref->value, List1_node, value));
+
+ printf("list1:");
+ c_foreach (i, List1, list1) printf(" %d", *i.ref);
+ printf("\nlist2:");
+ c_foreach (i, List2, list2) printf(" %d", i.ref->value);
+
+ printf("\nsort list1");
+ List1_sort(&list1);
+
+ printf("\nlist1:");
+ c_foreach (i, List1, list1) printf(" %d", *i.ref);
+ printf("\nlist2:");
+ c_foreach (i, List2, list2) printf(" %d", i.ref->value);
+
+ printf("\nremove 5 from both lists in O(1) time");
+ List1_iter it1 = List1_find(&list1, 5);
+ if (it1.ref) {
+ List1_unlink_node_after(&list1, it1.prev);
+ free(List2_unlink_node_after(&list2, c_container_of(it1.prev, List2_node, value)));
+ }
+ printf("\nlist1:");
+ c_foreach (i, List1, list1) printf(" %d", *i.ref);
+ printf("\nlist2:");
+ c_foreach (i, List2, list2) printf(" %d", i.ref->value);
+ puts("");
+ }
+}