dynarray.h 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public License
  6. * as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public License
  15. * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  16. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #ifndef AVUTIL_DYNARRAY_H
  19. #define AVUTIL_DYNARRAY_H
  20. #include "log.h"
  21. #include "mem.h"
  22. /**
  23. * Add an element to a dynamic array.
  24. *
  25. * The array is reallocated when its number of elements reaches powers of 2.
  26. * Therefore, the amortized cost of adding an element is constant.
  27. *
  28. * In case of success, the pointer to the array is updated in order to
  29. * point to the new grown array, and the size is incremented.
  30. *
  31. * @param av_size_max maximum size of the array, usually the MAX macro of
  32. * the type of the size
  33. * @param av_elt_size size of the elements in the array, in bytes
  34. * @param av_array pointer to the array, must be a lvalue
  35. * @param av_size size of the array, must be an integer lvalue
  36. * @param av_success statement to execute on success; at this point, the
  37. * size variable is not yet incremented
  38. * @param av_failure statement to execute on failure; if this happens, the
  39. * array and size are not changed; the statement can end
  40. * with a return or a goto
  41. */
  42. #define FF_DYNARRAY_ADD(av_size_max, av_elt_size, av_array, av_size, \
  43. av_success, av_failure) \
  44. do { \
  45. size_t av_size_new = (av_size); \
  46. if (!((av_size) & ((av_size) - 1))) { \
  47. av_size_new = (av_size) ? (av_size) << 1 : 1; \
  48. if (av_size_new > (av_size_max) / (av_elt_size)) { \
  49. av_size_new = 0; \
  50. } else { \
  51. void *av_array_new = \
  52. av_realloc((av_array), av_size_new * (av_elt_size)); \
  53. if (!av_array_new) \
  54. av_size_new = 0; \
  55. else \
  56. (av_array) = av_array_new; \
  57. } \
  58. } \
  59. if (av_size_new) { \
  60. { av_success } \
  61. (av_size)++; \
  62. } else { \
  63. av_failure \
  64. } \
  65. } while (0)
  66. #endif /* AVUTIL_DYNARRAY_H */