debugcounter.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * @file debugcounter.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. * Counter for detecting leaks.
  25. */
  26. #ifndef BADVPN_MISC_DEBUGCOUNTER_H
  27. #define BADVPN_MISC_DEBUGCOUNTER_H
  28. #include <stdint.h>
  29. #include <misc/debug.h>
  30. /**
  31. * Counter for detecting leaks.
  32. */
  33. typedef struct {
  34. #ifndef NDEBUG
  35. int32_t c;
  36. #endif
  37. } DebugCounter;
  38. #ifndef NDEBUG
  39. #define DEBUGCOUNTER_STATIC { .c = 0 }
  40. #else
  41. #define DEBUGCOUNTER_STATIC {}
  42. #endif
  43. /**
  44. * Initializes the object.
  45. * The object is initialized with counter value zero.
  46. *
  47. * @param obj the object
  48. */
  49. static void DebugCounter_Init (DebugCounter *obj)
  50. {
  51. #ifndef NDEBUG
  52. obj->c = 0;
  53. #endif
  54. }
  55. /**
  56. * Frees the object.
  57. * This does not have to be called when the counter is no longer needed.
  58. * The counter value must be zero.
  59. *
  60. * @param obj the object
  61. */
  62. static void DebugCounter_Free (DebugCounter *obj)
  63. {
  64. #ifndef NDEBUG
  65. ASSERT(obj->c == 0 || obj->c == INT32_MAX)
  66. #endif
  67. }
  68. /**
  69. * Increments the counter.
  70. * Increments the counter value by one.
  71. *
  72. * @param obj the object
  73. */
  74. static void DebugCounter_Increment (DebugCounter *obj)
  75. {
  76. #ifndef NDEBUG
  77. ASSERT(obj->c >= 0)
  78. if (obj->c != INT32_MAX) {
  79. obj->c++;
  80. }
  81. #endif
  82. }
  83. /**
  84. * Decrements the counter.
  85. * The counter value must be >0.
  86. * Decrements the counter value by one.
  87. *
  88. * @param obj the object
  89. */
  90. static void DebugCounter_Decrement (DebugCounter *obj)
  91. {
  92. #ifndef NDEBUG
  93. ASSERT(obj->c > 0)
  94. if (obj->c != INT32_MAX) {
  95. obj->c--;
  96. }
  97. #endif
  98. }
  99. #endif