minmax.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* CC0 (Public domain) - see LICENSE file for details */
  2. #ifndef CCAN_MINMAX_H
  3. #define CCAN_MINMAX_H
  4. #include "config.h"
  5. #include <ccan/build_assert/build_assert.h>
  6. #if !HAVE_STATEMENT_EXPR || !HAVE_TYPEOF
  7. /*
  8. * Without these, there's no way to avoid unsafe double evaluation of
  9. * the arguments
  10. */
  11. #error Sorry, minmax module requires statement expressions and typeof
  12. #endif
  13. #if HAVE_BUILTIN_TYPES_COMPATIBLE_P
  14. #define MINMAX_ASSERT_COMPATIBLE(a, b) \
  15. BUILD_ASSERT(__builtin_types_compatible_p(a, b))
  16. #else
  17. #define MINMAX_ASSERT_COMPATIBLE(a, b) \
  18. do { } while (0)
  19. #endif
  20. #define min(a, b) \
  21. ({ \
  22. typeof(a) _a = (a); \
  23. typeof(b) _b = (b); \
  24. MINMAX_ASSERT_COMPATIBLE(typeof(_a), typeof(_b)); \
  25. _a < _b ? _a : _b; \
  26. })
  27. #define max(a, b) \
  28. ({ \
  29. typeof(a) _a = (a); \
  30. typeof(b) _b = (b); \
  31. MINMAX_ASSERT_COMPATIBLE(typeof(_a), typeof(_b)); \
  32. _a > _b ? _a : _b; \
  33. })
  34. #define clamp(v, f, c) (max(min((v), (c)), (f)))
  35. #define min_t(t, a, b) \
  36. ({ \
  37. t _ta = (a); \
  38. t _tb = (b); \
  39. min(_ta, _tb); \
  40. })
  41. #define max_t(t, a, b) \
  42. ({ \
  43. t _ta = (a); \
  44. t _tb = (b); \
  45. max(_ta, _tb); \
  46. })
  47. #define clamp_t(t, v, f, c) \
  48. ({ \
  49. t _tv = (v); \
  50. t _tf = (f); \
  51. t _tc = (c); \
  52. clamp(_tv, _tf, _tc); \
  53. })
  54. #endif /* CCAN_MINMAX_H */