From 680d5fe9ad91c73100cb0a581ec7a6f1c41b7b07 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Mon, 7 Jul 2025 12:50:11 -0400 Subject: bfs.h: New container_of macro --- src/bfs.h | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/bfs.h b/src/bfs.h index 078feed..bb83df2 100644 --- a/src/bfs.h +++ b/src/bfs.h @@ -8,6 +8,9 @@ #ifndef BFS_H #define BFS_H +#include // For __GLIBC__ +#include // For offsetof + // Standard versions /** Possible __STDC_VERSION__ values. */ @@ -53,11 +56,18 @@ extern const char bfs_cflags[]; extern const char bfs_ldflags[]; extern const char bfs_ldlibs[]; -// Get __GLIBC__ -#include - // Fundamental utilities +/** + * Given `ptr = &t->member`, return `t`. + */ +#define container_of(ptr, type, member) \ + (container_of_typecheck(ptr, type, member), \ + (type *)((char *)ptr - offsetof(type, member))) + +#define container_of_typecheck(ptr, type, field) \ + (void)sizeof(ptr - &((type *)NULL)->field) + /** * A preprocessor conditional. * -- cgit v1.2.3