File tree Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change 13
13
* one.
14
14
*/
15
15
16
+ #include <stddef.h>
16
17
#include <string.h>
17
18
#include <stdint.h>
18
19
69
70
/** Length of a C static array. */
70
71
#define csnip_Static_len (a ) (sizeof(a) / sizeof(*(a)))
71
72
73
+ /** Find the containing struct of a pointer to a member.
74
+ *
75
+ * @param ptr
76
+ * pointer to a member variable.
77
+ *
78
+ * @param type
79
+ * The type of the container.
80
+ *
81
+ * @param member
82
+ * The name of the container member.
83
+ */
84
+ #define csnip_Container_of (ptr , type , member ) \
85
+ ((type*)(((char*)ptr) - offsetof(type, member)))
86
+
72
87
/** Compute the next power of 2 of a number. */
73
88
inline size_t csnip_next_pow_of_2 (size_t a )
74
89
{
@@ -149,6 +164,7 @@ inline size_t csnip_next_pow_of_2(size_t a)
149
164
#define Max csnip_Max
150
165
#define Clamp csnip_Clamp
151
166
#define Static_len csnip_Static_len
167
+ #define Container_of csnip_Container_of
152
168
#define next_pow_of_2 csnip_next_pow_of_2
153
169
#define Fill_n csnip_Fill_n
154
170
#define Fill csnip_Fill
Original file line number Diff line number Diff line change @@ -39,10 +39,23 @@ void test_clamp(void)
39
39
CHECK (Clamp (-3 , 5 , 3 ) == 3 );
40
40
}
41
41
42
+ struct X {
43
+ int u ;
44
+ double v ;
45
+ };
46
+
47
+ void test_container_of (void )
48
+ {
49
+ struct X c ;
50
+ CHECK (Container_of (& c .v , struct X , v ) == & c );
51
+ CHECK (Container_of (& c .u , struct X , u ) == & c );
52
+ }
53
+
42
54
int main (void )
43
55
{
44
56
test_min ();
45
57
test_max ();
46
58
test_clamp ();
59
+ test_container_of ();
47
60
return 0 ;
48
61
}
You can’t perform that action at this time.
0 commit comments