exparray.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @file exparray.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. * Dynamic array which grows exponentionally on demand.
  25. */
  26. #ifndef BADVPN_MISC_EXPARRAY_H
  27. #define BADVPN_MISC_EXPARRAY_H
  28. #include <stddef.h>
  29. #include <stdlib.h>
  30. #include <limits.h>
  31. #include <misc/debug.h>
  32. struct ExpArray {
  33. size_t esize;
  34. size_t size;
  35. void *v;
  36. };
  37. static int ExpArray_init (struct ExpArray *o, size_t esize, size_t size)
  38. {
  39. ASSERT(esize > 0)
  40. ASSERT(size > 0)
  41. o->esize = esize;
  42. o->size = size;
  43. if (o->size > SIZE_MAX / o->esize) {
  44. return 0;
  45. }
  46. if (!(o->v = malloc(o->size * o->esize))) {
  47. return 0;
  48. }
  49. return 1;
  50. }
  51. static int ExpArray_resize (struct ExpArray *o, size_t size)
  52. {
  53. ASSERT(size > 0)
  54. if (size <= o->size) {
  55. return 1;
  56. }
  57. size_t newsize = o->size;
  58. while (newsize < size) {
  59. if (2 > SIZE_MAX / newsize) {
  60. return 0;
  61. }
  62. newsize = 2 * newsize;
  63. }
  64. if (newsize > SIZE_MAX / o->esize) {
  65. return 0;
  66. }
  67. void *newarr = realloc(o->v, newsize * o->esize);
  68. if (!newarr) {
  69. return 0;
  70. }
  71. o->size = newsize;
  72. o->v = newarr;
  73. return 1;
  74. }
  75. #endif