summaryrefslogtreecommitdiff
path: root/lab02/container_of.h
blob: 87fb6d4f7579a0a9447c94c47599d8e68a194051 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _CONTAINER_OF_H
#define _CONTAINER_OF_H

#include <stddef.h>

#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))

#undef offsetof
#define offsetof(TYPE, MEMBER)	__builtin_offsetof(TYPE, MEMBER)

#define typeof_member(T, m)   typeof(((T*)0)->m)

/**
 * 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) ({                         \
    _Static_assert(__same_type(*(ptr), typeof_member(type, member)) || \
                   __same_type(*(ptr), void),                      \
                   "pointer type mismatch in container_of()");     \
    (type *)((void *)(ptr) - offsetof(type, member)); })


#define container_of_const(ptr, type, member)				\
	_Generic(ptr,							\
		const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
		default: ((type *)container_of(ptr, type, member))	\
	)

#endif /* _CONTAINER_OF_H */