PatchworkOS  da8a090
A non-POSIX operating system.
Loading...
Searching...
No Matches
CONTAINER_OF.h
Go to the documentation of this file.
1#ifndef _AUX_CONTAINER_OF_H
2#define _AUX_CONTAINER_OF_H 1
3
4#include <stddef.h>
5
6/**
7 * @brief Container of macro
8 * @ingroup libstd
9 *
10 * The `CONTAINER_OF()` macro can be used to retrieve the parent structure given a pointer to a member of that
11 * structure.
12 *
13 * @param ptr The pointer to the structures member.
14 * @param type The name of the perent structures type.
15 * @param member The name of the member that `ptr` points to.
16 * @return A pointer to the parent structure.
17 */
18#define CONTAINER_OF(ptr, type, member) ((type*)((char*)(ptr) - offsetof(type, member)))
19
20/**
21 * @brief Safe container of macro.
22 * @ingroup libstd
23 *
24 * The `CONTAINER_OF_SAFE()` macro is the same as the `CONTAINER_OF()`, expect that it also handles `NULL` values.
25 *
26 * @param ptr The pointer to the structures member.
27 * @param type The name of the perent structures type.
28 * @param member The name of the member that `ptr` points to.
29 * @return If `ptr` is not equal to `NULL`, returns a pointer to the parent structure, else returns `NULL`.
30 */
31#define CONTAINER_OF_SAFE(ptr, type, member) \
32 ({ \
33 void* p = ptr; \
34 ((p != NULL) ? CONTAINER_OF(p, type, member) : NULL); \
35 })
36
37#endif