check_type.h 2.3 KB

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