overflow.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * @file overflow.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Functions for checking for overflow of integer addition.
  25. */
  26. #ifndef BADVPN_MISC_OVERFLOW_H
  27. #define BADVPN_MISC_OVERFLOW_H
  28. #include <limits.h>
  29. #include <stdint.h>
  30. #define DEFINE_UNSIGNED_OVERFLOW(_name, _type, _max) \
  31. static int add_ ## _name ## _overflows (_type a, _type b) \
  32. {\
  33. return (b > _max - a); \
  34. }
  35. #define DEFINE_SIGNED_OVERFLOW(_name, _type, _min, _max) \
  36. static int add_ ## _name ## _overflows (_type a, _type b) \
  37. {\
  38. if ((a < 0) ^ (b < 0)) return 0; \
  39. if (a < 0) return -(a < _min - b); \
  40. return (a > _max - b); \
  41. }
  42. DEFINE_UNSIGNED_OVERFLOW(uint, unsigned int, UINT_MAX)
  43. DEFINE_UNSIGNED_OVERFLOW(uint8, uint8_t, UINT8_MAX)
  44. DEFINE_UNSIGNED_OVERFLOW(uint16, uint16_t, UINT16_MAX)
  45. DEFINE_UNSIGNED_OVERFLOW(uint32, uint32_t, UINT32_MAX)
  46. DEFINE_UNSIGNED_OVERFLOW(uint64, uint64_t, UINT64_MAX)
  47. DEFINE_SIGNED_OVERFLOW(int, int, INT_MIN, INT_MAX)
  48. DEFINE_SIGNED_OVERFLOW(int8, int8_t, INT8_MIN, INT8_MAX)
  49. DEFINE_SIGNED_OVERFLOW(int16, int16_t, INT16_MIN, INT16_MAX)
  50. DEFINE_SIGNED_OVERFLOW(int32, int32_t, INT32_MIN, INT32_MAX)
  51. DEFINE_SIGNED_OVERFLOW(int64, int64_t, INT64_MIN, INT64_MAX)
  52. #endif