]> git.ozlabs.org Git - ccan/blob - ccan/container_of/container_of.h
ec66f106f2aeb0144b17455973607b873ae88731
[ccan] / ccan / container_of / container_of.h
1 #ifndef CCAN_CONTAINER_OF_H
2 #define CCAN_CONTAINER_OF_H
3 #include <stddef.h>
4
5 #include "config.h"
6 #include <ccan/check_type/check_type.h>
7
8 /**
9  * container_of - get pointer to enclosing structure
10  * @member_ptr: pointer to the structure member
11  * @containing_type: the type this member is within
12  * @member: the name of this member within the structure.
13  *
14  * Given a pointer to a member of a structure, this macro does pointer
15  * subtraction to return the pointer to the enclosing type.
16  *
17  * Example:
18  *      struct info
19  *      {
20  *              int some_other_field;
21  *              struct foo my_foo;
22  *      };
23  *
24  *      struct info *foo_to_info(struct foo *foop)
25  *      {
26  *              return container_of(foo, struct info, my_foo);
27  *      }
28  */
29 #define container_of(member_ptr, containing_type, member)               \
30          ((containing_type *)                                           \
31           ((char *)(member_ptr) - offsetof(containing_type, member))    \
32           - check_types_match(*(member_ptr), ((containing_type *)0)->member))
33
34
35 /**
36  * container_of_var - get pointer to enclosing structure using a variable
37  * @member_ptr: pointer to the structure member
38  * @var: a pointer to a structure of same type as this member is within
39  * @member: the name of this member within the structure.
40  *
41  * Given a pointer to a member of a structure, this macro does pointer
42  * subtraction to return the pointer to the enclosing type.
43  *
44  * Example:
45  *      struct info
46  *      {
47  *              int some_other_field;
48  *              struct foo my_foo;
49  *      };
50  *
51  *      struct info *foo_to_info(struct foo *foop)
52  *      {
53  *              struct info *i = container_of_var(foo, i, my_foo);
54  *              return i;
55  *      }
56  */
57 #ifdef HAVE_TYPEOF
58 #define container_of_var(member_ptr, var, member) \
59         container_of(member_ptr, typeof(*var), member)
60 #else
61 #define container_of_var(member_ptr, var, member) \
62         ((void *)((char *)(member_ptr) - offsetof(containing_type, member)))
63 #endif
64
65 #endif /* CCAN_CONTAINER_OF_H */