]> git.ozlabs.org Git - ccan/blob - ccan/check_type/check_type.h
check_type: fix incorrect documentation.
[ccan] / ccan / check_type / check_type.h
1 #ifndef CCAN_CHECK_TYPE_H
2 #define CCAN_CHECK_TYPE_H
3 #include "config.h"
4
5 /**
6  * check_type - issue a warning or build failure if type is not correct.
7  * @expr: the expression whose type we should check (not evaluated).
8  * @type: the exact type we expect the expression to be.
9  *
10  * This macro is usually used within other macros to try to ensure that a macro
11  * argument is of the expected type.  No type promotion of the expression is
12  * done: an unsigned int is not the same as an int!
13  *
14  * check_type() always evaluates to 0.
15  *
16  * If your compiler does not support typeof, then the best we can do is fail
17  * to compile if the sizes of the types are unequal (a less complete check).
18  *
19  * Example:
20  *      // They should always pass a 64-bit value to _set_some_value!
21  *      #define set_some_value(expr)                    \
22  *              _set_some_value((check_type((expr), uint64_t), (expr)))
23  */
24
25 /**
26  * check_types_match - issue a warning or build failure if types are not same.
27  * @expr1: the first expression (not evaluated).
28  * @expr2: the second expression (not evaluated).
29  *
30  * This macro is usually used within other macros to try to ensure that
31  * arguments are of identical types.  No type promotion of the expressions is
32  * done: an unsigned int is not the same as an int!
33  *
34  * check_types_match() always evaluates to 0.
35  *
36  * If your compiler does not support typeof, then the best we can do is fail
37  * to compile if the sizes of the types are unequal (a less complete check).
38  *
39  * Example:
40  *      // Do subtraction to get to enclosing type, but make sure that
41  *      // pointer is of correct type for that member. 
42  *      #define container_of(mbr_ptr, encl_type, mbr)                   \
43  *              (check_types_match((mbr_ptr), &((encl_type *)0)->mbr),  \
44  *               ((encl_type *)                                         \
45  *                ((char *)(mbr_ptr) - offsetof(enclosing_type, mbr))))
46  */
47 #if HAVE_TYPEOF
48 #define check_type(expr, type)                  \
49         ((typeof(expr) *)0 != (type *)0)
50
51 #define check_types_match(expr1, expr2)         \
52         ((typeof(expr1) *)0 != (typeof(expr2) *)0)
53 #else
54 #include <ccan/build_assert/build_assert.h>
55 /* Without typeof, we can only test the sizes. */
56 #define check_type(expr, type)                                  \
57         BUILD_ASSERT_OR_ZERO(sizeof(expr) == sizeof(type))
58
59 #define check_types_match(expr1, expr2)                         \
60         BUILD_ASSERT_OR_ZERO(sizeof(expr1) == sizeof(expr2))
61 #endif /* HAVE_TYPEOF */
62
63 #endif /* CCAN_CHECK_TYPE_H */