summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2025-07-07 12:50:11 -0400
committerTavian Barnes <tavianator@tavianator.com>2025-07-26 14:19:52 -0400
commit680d5fe9ad91c73100cb0a581ec7a6f1c41b7b07 (patch)
tree14a731f9e5d2e9392ffcef98bc5eea5fe65c8763
parent3e4787b7ac8cb28a1125ebc1e042d00bc58a91b5 (diff)
downloadbfs-680d5fe9ad91c73100cb0a581ec7a6f1c41b7b07.tar.xz
bfs.h: New container_of macro
-rw-r--r--src/bfs.h16
1 files changed, 13 insertions, 3 deletions
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 <assert.h> // For __GLIBC__
+#include <stddef.h> // For offsetof
+
// Standard versions
/** Possible __STDC_VERSION__ values. */
@@ -53,12 +56,19 @@ extern const char bfs_cflags[];
extern const char bfs_ldflags[];
extern const char bfs_ldlibs[];
-// Get __GLIBC__
-#include <assert.h>
-
// 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.
*
* BFS_VA_IF(A)(B)(C) => B