list.h: add container_of_safe macro
authorFelix Fietkau <nbd@nbd.name>
Fri, 29 Apr 2022 10:57:25 +0000 (12:57 +0200)
committerFelix Fietkau <nbd@nbd.name>
Fri, 29 Apr 2022 10:57:52 +0000 (12:57 +0200)
It works like container_of, except that it also deals with NULL pointers

Signed-off-by: Felix Fietkau <nbd@nbd.name>
list.h

diff --git a/list.h b/list.h
index a2cb24168a951ea76e094df473f6a31623169432..6aa7b2abdc3d6a552b74dfc102070ba9b980ac5f 100644 (file)
--- a/list.h
+++ b/list.h
        })
 #endif
 
+#ifndef container_of_safe
+#define container_of_safe(ptr, type, member)                                           \
+       ({                                                                              \
+               const __typeof__(((type *) NULL)->member) *__mptr = (ptr);              \
+               __mptr ? (type *)((char *) __mptr - offsetof(type, member)) : NULL;     \
+       })
+#endif
+
 struct list_head {
        struct list_head *next;
        struct list_head *prev;