dynarray_emplace_enlarge.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Increase the size of a dynamic array in preparation of an emplace operation.
  2. Copyright (C) 2017-2023 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #ifndef _LIBC
  16. # include <libc-config.h>
  17. #endif
  18. #include <dynarray.h>
  19. #include <errno.h>
  20. #include <intprops.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. bool
  24. __libc_dynarray_emplace_enlarge (struct dynarray_header *list,
  25. void *scratch, size_t element_size)
  26. {
  27. size_t new_allocated;
  28. if (list->allocated == 0)
  29. {
  30. /* No scratch buffer provided. Choose a reasonable default
  31. size. */
  32. if (element_size < 4)
  33. new_allocated = 16;
  34. else if (element_size < 8)
  35. new_allocated = 8;
  36. else
  37. new_allocated = 4;
  38. }
  39. else
  40. /* Increase the allocated size, using an exponential growth
  41. policy. */
  42. {
  43. new_allocated = list->allocated + list->allocated / 2 + 1;
  44. if (new_allocated <= list->allocated)
  45. {
  46. /* Overflow. */
  47. __set_errno (ENOMEM);
  48. return false;
  49. }
  50. }
  51. size_t new_size;
  52. if (INT_MULTIPLY_WRAPV (new_allocated, element_size, &new_size))
  53. return false;
  54. void *new_array;
  55. if (list->array == scratch)
  56. {
  57. /* The previous array was not heap-allocated. */
  58. new_array = malloc (new_size);
  59. if (new_array != NULL && list->array != NULL)
  60. memcpy (new_array, list->array, list->used * element_size);
  61. }
  62. else
  63. new_array = realloc (list->array, new_size);
  64. if (new_array == NULL)
  65. return false;
  66. list->array = new_array;
  67. list->allocated = new_allocated;
  68. return true;
  69. }
  70. libc_hidden_def (__libc_dynarray_emplace_enlarge)