From 6156fcbbb5c1f123ebda3a4df4beaba9efcc68ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nils=20O=2E=20Sel=C3=A5sdal?= Date: Thu, 28 Nov 2013 18:30:14 +0100 Subject: [PATCH] Add tailq example --- test/tailq_example.c | 89 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 test/tailq_example.c diff --git a/test/tailq_example.c b/test/tailq_example.c new file mode 100644 index 0000000..11419b6 --- /dev/null +++ b/test/tailq_example.c @@ -0,0 +1,89 @@ +#include +#include +#include +#include +#include + +struct Block { + char text[64]; + struct TailQ blocks; +}; + +struct File { + char name[128]; + struct TailQ head; +}; + +void add_block(struct File *f, const char *txt) +{ + struct Block *b = malloc(sizeof *b); + strcpy(b->text,txt); + uc_tailq_insert_tail(&f->head, &b->blocks); +} + +void print_file(struct File *f) +{ + struct TailQ *entry; + printf("File: %s\n", f->name); + UC_TAILQ_FOREACH(entry, &f->head) { + struct Block *b = UC_CONTAINER_OF(entry, struct Block, blocks); + printf("Block: %s\n", b->text); + } +} + +void delete_block(struct File *f, const char *txt) +{ + struct TailQ *entry, *next; + UC_TAILQ_FOREACH_SAFE(entry, next, &f->head) { + struct Block *b = UC_CONTAINER_OF(entry, struct Block, blocks); + if (strcmp(txt, b->text) == 0) { + uc_tailq_remove(entry); + free(b); + } + } +} + +void delete_all_blocks(struct File *f) +{ + struct TailQ *entry, *next; + UC_TAILQ_FOREACH_SAFE(entry, next, &f->head) { + struct Block *b = UC_CONTAINER_OF(entry, struct Block, blocks); + free(b); + } + uc_tailq_init(&f->head); +} + +int main(void) +{ + struct File f; + uc_tailq_init(&f.head); + printf("Is Empty: %d\n", uc_tailq_empty(&f.head)); + strcpy(f.name,"Test.f"); + add_block(&f,"one"); + add_block(&f,"two"); + add_block(&f,"three"); + + print_file(&f); + printf("Is Empty: %d\n", uc_tailq_empty(&f.head)); + + puts("\nDeleting three"); + delete_block(&f, "three"); + print_file(&f); + + puts("\nAdding 2 blocks"); + add_block(&f,"three"); + add_block(&f,"three"); + print_file(&f); + + puts("\nDeleting three"); + delete_block(&f, "three"); + print_file(&f); + + delete_all_blocks(&f); + printf("Is Empty: %d\n", uc_tailq_empty(&f.head)); + + + return 0; +} + +