container.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2014 Freie Universität Berlin
3  * 2017 HAW-Hamburg
4  *
5  * This file is subject to the terms and conditions of the GNU Lesser
6  * General Public License v2.1. See the file LICENSE in the top level
7  * directory for more details.
8  */
9 
10 #pragma once
11 
23 #include <stddef.h>
24 #include <stdint.h>
25 
26 #ifdef __cplusplus
27 extern "C" {
28 #endif
29 
30 /* uncrustify gets mightily confused by these macros... */
31 /* begin{code-style-ignore} */
32 
46 #if __STDC_VERSION__ >= 201112L
47 # define container_of(PTR, TYPE, MEMBER) \
48  (_Generic((PTR), \
49  const __typeof__ (((TYPE *) 0)->MEMBER) *: \
50  ((TYPE *) ((uintptr_t) (PTR) - offsetof(TYPE, MEMBER))), \
51  __typeof__ (((TYPE *) 0)->MEMBER) *: \
52  ((TYPE *) ((uintptr_t) (PTR) - offsetof(TYPE, MEMBER))) \
53  ))
54 #elif defined __GNUC__
55 # define container_of(PTR, TYPE, MEMBER) \
56  (__extension__ ({ \
57  __extension__ const __typeof__ (((TYPE *) 0)->MEMBER) *__m____ = (PTR); \
58  ((TYPE *) ((uintptr_t) __m____ - offsetof(TYPE, MEMBER))); \
59  }))
60 #else
61 # define container_of(PTR, TYPE, MEMBER) \
62  ((TYPE *) ((char *) (PTR) - offsetof(TYPE, MEMBER)))
63 #endif
64 
73 #define index_of(ARRAY, ELEMENT) (((uintptr_t)(ELEMENT) - (uintptr_t)(ARRAY)) / sizeof((ARRAY)[0]))
74 
81 #ifndef ARRAY_SIZE
82 #define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
83 #endif
84 
85 #ifdef __cplusplus
86 }
87 #endif
88