chiark / gitweb /
util: introduce container_of() macro
authorLucas De Marchi <lucas.demarchi@profusion.mobi>
Thu, 26 Apr 2012 16:36:01 +0000 (13:36 -0300)
committerKay Sievers <kay@vrfy.org>
Sun, 29 Apr 2012 17:14:05 +0000 (19:14 +0200)
This macro comes from kernel and it's useful for unwrapping structs
inside another one. The generated code is actually the same to the one
where this logic is used in udev, but using this macro is much cleaner
and less error prone.

src/shared/util.h

index 17ffd19f55415cfc0c4759021df1d442c14f3fe2..0246dfd826c40d417e95ac4d1630db61a09f1e31 100644 (file)
@@ -59,6 +59,17 @@ typedef struct dual_timestamp {
 #define USEC_PER_MONTH (2629800ULL*USEC_PER_SEC)
 #define USEC_PER_YEAR (31557600ULL*USEC_PER_SEC)
 
 #define USEC_PER_MONTH (2629800ULL*USEC_PER_SEC)
 #define USEC_PER_YEAR (31557600ULL*USEC_PER_SEC)
 
+/*
+ * container_of - cast a member of a structure out to the containing structure
+ * @ptr: the pointer to the member.
+ * @type: the type of the container struct this is embedded in.
+ * @member: the name of the member within the struct.
+ *
+ */
+#define container_of(ptr, type, member) ({ \
+        const typeof( ((type *)0)->member ) *__mptr = (ptr); \
+        (type *)( (char *)__mptr - offsetof(type,member) );})
+
 /* What is interpreted as whitespace? */
 #define WHITESPACE " \t\n\r"
 #define NEWLINE "\n\r"
 /* What is interpreted as whitespace? */
 #define WHITESPACE " \t\n\r"
 #define NEWLINE "\n\r"