Skip to content

Instantly share code, notes, and snippets.

@mrjohannchang
Last active March 28, 2025 11:23
Show Gist options
  • Save mrjohannchang/89ad789c0cb960fb93109f7d1bd1a9ff to your computer and use it in GitHub Desktop.
Save mrjohannchang/89ad789c0cb960fb93109f7d1bd1a9ff to your computer and use it in GitHub Desktop.
C23 find in sys/queue
#pragma once
#include <sys/queue.h>
#define find_in_slist(element, list_head, entry_name, comparator) \
({ \
typeof(element) ret = nullptr; \
typeof(element) current_element = nullptr; \
SLIST_FOREACH(current_element, list_head, entry_name) { \
if (comparator(current_element, element)) { \
ret = current_element; \
break; \
} \
} \
ret; \
})
#define find_in_stailq(element, queue_head, entry_name, comparator) \
({ \
typeof(element) ret = nullptr; \
typeof(element) current_element = nullptr; \
STAILQ_FOREACH(current_element, queue_head, entry_name) { \
if (comparator(current_element, element)) { \
ret = current_element; \
break; \
} \
} \
ret; \
})
#define find_in_list(element, list_head, entry_name, comparator) \
({ \
typeof(element) ret = nullptr; \
typeof(element) current_element = nullptr; \
LIST_FOREACH(current_element, list_head, entry_name) { \
if (comparator(current_element, element)) { \
ret = current_element; \
break; \
} \
} \
ret; \
})
#define find_in_tailq(element, queue_head, entry_name, comparator) \
({ \
typeof(element) ret = nullptr; \
typeof(element) current_element = nullptr; \
TAILQ_FOREACH(current_element, queue_head, entry_name) { \
if (comparator(current_element, element)) { \
ret = current_element; \
break; \
} \
} \
ret; \
})
#include <stdio.h>
#include <string.h>
#include <sys/queue.h>
#include "find_in_list.h"
typedef struct my_list_element {
char my_string[12];
int my_number;
TAILQ_ENTRY(my_list_element) entry;
} my_list_element_t;
bool my_list_element_comparator(
my_list_element_t* element1, my_list_element_t* element2) {
return strcmp(element1->my_string, element2->my_string) == 0;
}
TAILQ_HEAD(my_list, my_list_element);
int main(int argc, char* argv[]) {
struct my_list my_list_head;
TAILQ_INIT(&my_list_head);
my_list_element_t element1 = { .my_string = "element1", .my_number = 1 };
TAILQ_INSERT_TAIL(&my_list_head, &element1, entry);
my_list_element_t element1_clone = { .my_string = "element1",
.my_number = 1 };
my_list_element_t element2 = { .my_string = "element2", .my_number = 2 };
my_list_element_t* element_p = find_in_tailq(
&element1_clone, &my_list_head, entry, my_list_element_comparator);
if (element_p) {
printf("element1_clone is in the list\n");
} else {
printf("element1_clone is not in the list\n");
}
element_p = find_in_tailq(
&element2, &my_list_head, entry, my_list_element_comparator);
if (element_p) {
printf("element2 is in the list\n");
} else {
printf("element2 is not in the list\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment