modadd.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @file modadd.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. * Modular addition macro.
  25. *
  26. * Calculates (x + y) mod m, assuming
  27. * 0 <= x < m and 0 <= y < m.
  28. */
  29. #ifndef BADVPN_MISC_MODADD_H
  30. #define BADVPN_MISC_MODADD_H
  31. #include <misc/debug.h>
  32. #define DECLARE_BMODADD(type, name) \
  33. static type bmodadd_##name (type x, type y, type m) \
  34. { \
  35. ASSERT(x >= 0) \
  36. ASSERT(x < m) \
  37. ASSERT(y >= 0) \
  38. ASSERT(y < m) \
  39. \
  40. if (y >= m - x) { \
  41. return (y - (m - x)); \
  42. } else { \
  43. return (x + y); \
  44. } \
  45. } \
  46. DECLARE_BMODADD(int, int)
  47. #endif