balign.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @file balign.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. * Integer alignment macros.
  25. */
  26. #ifndef BADVPN_MISC_BALIGN_H
  27. #define BADVPN_MISC_BALIGN_H
  28. #include <stddef.h>
  29. #include <stdint.h>
  30. /**
  31. * Checks if aligning x up to n would overflow.
  32. */
  33. static int balign_up_overflows (size_t x, size_t n)
  34. {
  35. size_t r = x % n;
  36. return (r && x > SIZE_MAX - (n - r));
  37. }
  38. /**
  39. * Aligns x up to n.
  40. */
  41. static size_t balign_up (size_t x, size_t n)
  42. {
  43. size_t r = x % n;
  44. return (r ? x + (n - r) : x);
  45. }
  46. /**
  47. * Aligns x down to n.
  48. */
  49. static size_t balign_down (size_t x, size_t n)
  50. {
  51. return (x - (x % n));
  52. }
  53. /**
  54. * Calculates the quotient of a and b, rounded up.
  55. */
  56. static size_t bdivide_up (size_t a, size_t b)
  57. {
  58. size_t r = a % b;
  59. return (r > 0 ? a / b + 1 : a / b);
  60. }
  61. #endif